【问题标题】:How to catch a fatal error both in PHP 7 and 8?如何捕捉 PHP 7 和 8 中的致命错误?
【发布时间】:2021-08-24 16:08:23
【问题描述】:

我有一个 PHP 7 脚本,基本上是这样做的:

try {
    $class = getClassFromSomewhere();
}
catch(Error $e) {
    if ("Class 'Main' not found" == $e->getMessage()) {
        echo 'Run "php generate-main-class" to generate the class.'.PHP_EOL;
        exit;
    } else {
        throw $e;
    }
}

明确一点:如果我正在寻找的类是“Main”并且找不到,我必须显示文本,否则无论如何它应该抛出异常。

它适用于 PHP 7,但 PHP 8 没有捕捉到错误。相反,它显示:

Fatal error: Uncaught Error: Class "Main" not found in ...

我应该如何以向后兼容的方式捕获 PHP 8 中的“找不到类”致命错误?

【问题讨论】:

  • getClassFromSomewhere()里面的代码是什么?
  • 刚刚使用 PHP 8 在线尝试过,消息是 Class "Main" not found - 注意引号。您正在测试"Class 'Main' not found"
  • @NigelRen,没错!它在 PHP 7 中是单引号,在 PHP 8 中是双引号。请将您的评论转换为答案,以便我接受!

标签: php error-handling try-catch


【解决方案1】:

唯一的区别似乎是 PHP 8 在类名周围使用了双引号 -

Class "Main" not found

而以前(如在您当前的代码中)使用单引号...

Class 'Main' not found

您也可以在尝试代码 (In PHP how can i check if class exists?) 之前检查类是否存在,这可能比导致错误更简洁。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-04
    • 2016-08-16
    • 2010-11-25
    • 2015-01-18
    • 1970-01-01
    • 2011-01-20
    • 2019-04-20
    相关资源
    最近更新 更多