我想
问我是否可以要求/包含有语法错误的文件,如果我不能,require/include 将返回一个值,以便我知道必需/包含的文件有语法错误并且不能要求/包含?
文件.php有语法错误
include('file.php')
if (not file.php included because of syntax)
this
else
that
如果你真的想要这种类型的功能。
您可以尝试使用nikics php解析器来查看是否可以成功解析文件。
$code = file_get_contents('yourFile.php');
$parser = new PhpParser'Parser(new PhpParser'Lexer'Emulative);
try {
$stmts = $parser->parse($code);
// $stmts is an array of statement nodes
// file can be successfully included!
} catch (PhpParser'Error $e) {
// cannot parse file!
echo 'Parse Error: ', $e->getMessage();
}
在 PHP 7 中,解析错误可以被捕获,这使得这可能是最健壮、最优雅的内置解决方案:
<?php
function safe_require_once(string $fname) {
try {
require_once($fname);
} catch( Throwable $e ) {
//will throw a warning, continuing execution...
trigger_error("safe_require_once() error '$e'", E_USER_WARNING);
}
}
safe_require_once("./test1.php"); //file with parse or runtime errors
echo "COMPLETED SUCCESSFULLY THO";
你可以使用以下内容:
if((@include $filename) === false)
{
// handle error
} else { //....}
@
用于隐藏错误消息