【发布时间】: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