【问题标题】:How to catch ParseError in Yii2 with PHP 7.1如何使用 PHP 7.1 在 Yii2 中捕获 ParseError
【发布时间】:2017-06-26 12:14:44
【问题描述】:

如果我从命令行尝试以下代码,它会正确捕获 ParseError:

<?php

$command = "[";

set_error_handler(function($errno, $errstr) {
throw new Exception($errstr);
}, E_ALL);
try {
    eval("\$command = $command;");
} catch (ParseError $e) {
    echo 'Caught parse error: ',  $e->getMessage(), "\n";
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

输出是:

$ php eval.php 
PHP ParseError:  syntax error, unexpected ';', expecting ']' in /home/ntibor/tmp/eval.php(9) : eval()'d code on line 1
PHP Stack trace:
PHP   1. {main}() /home/ntibor/tmp/eval.php:0
Caught parse error: syntax error, unexpected ';', expecting ']'

但是,如果我在 Yii2 中使用非常相似的代码,它不会捕获 ParseError:

   set_error_handler(function($errno, $errstr) {
        throw new \yii\base\Exception($errstr);
    }, E_ALL);
    try {
        eval("\$config = $this->calculation_formula;");
    } catch (ParseError $e) {
        restore_error_handler();
        return $e->getMessage();
    } catch (\yii\base\Exception $e) {
        restore_error_handler();
        return $e->getMessage();
    }
    restore_error_handler();

我在 Yii2 的供应商代码中没有发现任何关于 ParseError 的内容。 关于 E_PARSE,我没有看到 cli 和 apache2 php 配置之间有任何区别。

【问题讨论】:

  • [when eval"ing" 命令变成"\[ = [;" PHP 期待右方括号,即"\[] = [];""\$config = $this-&gt;calculation_formula;" 可能与 "\$command = $command; 不同
  • 这很清楚。问题是 ParseError 没有被捕获。我使用“[”来触发 ParseError。

标签: php exception-handling yii2 php-7


【解决方案1】:

如果我没记错的话,你需要像这样在catch里面的ParseError类声明中添加'\':

catch (\ParseError $e) {
    restore_error_handler();
    return $e->getMessage();
}

似乎与 Yii2 使用的 Loader 有关,这会影响 PHP 类的加载方式。

【讨论】:

    猜你喜欢
    • 2015-08-29
    • 1970-01-01
    • 2017-11-04
    • 1970-01-01
    • 2015-02-15
    • 2017-11-29
    • 1970-01-01
    • 2017-04-04
    • 2020-05-11
    相关资源
    最近更新 更多