如何捕获 php eval() 中的解析错误?

我想使用 php eval() 来识别潜在的解析错误。我知道评估的危险,但这是一个非常有限的用途,将事先进行充分验证。


我相信在 php 7 中我们应该能够捕获解析错误,但它不起作用。这是一个例子:


  $one = "hello";

  $two = " world";

  $three = '';

  $cmdstr = '$three = $one . $tw;';


  try {

     $result = eval($cmdstr);

 } catch (ParseError $e) {

     echo 'error: ' . $e;

 }


echo $three;

我试图在此处引发解析错误,看看是否可以捕获它,但是当我运行它时,错误(未定义的变量 tw)会像通常那样出现。它没有被抓住。


有什么想法如何从 eval 捕获解析错误吗?


撒科打诨
浏览 94回答 2
2回答

吃鸡游戏

您的代码无法按预期工作,因为在 PHP 中,未定义的变量不会触发解析错误,而是会触发通知。感谢set_error_handler本机函数,您可以将通知转换为错误,然后使用以下 PHP 7 代码捕获它:<?phpset_error_handler(function($_errno, $errstr) {    // Convert notice, warning, etc. to error.    throw new Error($errstr);});$one = "hello";$two = " world";$three = '';$cmdstr = '$three = $one . $tw;';try {    $result = eval($cmdstr);} catch (Throwable $e) {    echo $e; // Error: Undefined variable: tw...}echo $three;

largeQ

您的 PHP 代码会抛出“Notice”类型的错误,并且这些错误无法由 try..catch 块处理。您必须使用 PHP 的set_error_handler方法来使用自己的错误处理程序。阅读该文档,您就会明白该怎么做。如果您想要一个如何操作的示例,那么:<?phpfunction myErrorHandler($errno, $errstr){    switch ($errno) {        case E_USER_ERROR:            die("User Error");            break;        default:            die("Your own error");            break;    }    /* Don't execute PHP internal error handler */    return true;}$err = set_error_handler("myErrorhandler");$one = "hello";$two = " world";$three = '';$cmdstr = '$three = $one . $tw;';$result = eval($cmdstr);echo $three;?>
打开App,查看更多内容
随时随地看视频慕课网APP