我想请问,我可以要求/包括有语法错误,如果我不能,则需要/包括返回一个值,让我知道所需的文件/包含的文件有语法错误,不能被要求/包括在内?包括需要一个语法错误文件
file.php有语法错误
include('file.php')
if (not file.php included because of syntax)
this
else
that
我想请问,我可以要求/包括有语法错误,如果我不能,则需要/包括返回一个值,让我知道所需的文件/包含的文件有语法错误,不能被要求/包括在内?包括需要一个语法错误文件
file.php有语法错误
include('file.php')
if (not file.php included because of syntax)
this
else
that
如果你真的想要这种类型的功能。
你可以尝试使用nikics php parser,看是否可以成功地解析该文件或没有。
$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();
}
你可以使用的东西IKE在此:
if((@include $filename) === false)
{
// handle error
} else { //....}
的@
用来隐藏错误消息
在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";
这将隐藏包括本身的错误。操作询问关于语法错误。 – Federkun
@Leggendario如果是这样的问题,那么问题就没有意义了。在包含之前,PHP不检查这样的错误。它首先包括文件,然后读取它(反过来是不可能的,对不对?) – FeedTheWeb
如果包含的文件有语法错误,停止执行,即使有错误抑制。没有超过包括将工作。 – castis