从PHP 7开始,可以通过捕获Fatal Errors
类或Error
接口来捕获Throwable
,但出于某种原因,当触发“致命错误:未找到特征”时,我无法做到这一点。
try {
class Cars {
use Price;
}
} catch (Error $e) {
echo $e->getMessage(); // Output : Fatal error: Trait 'Price' not found in [..] on line [..]
}
没有抓到错误!!所以我想出了一个解决方案
try {
if (trait_exists('Price')) {
class Cars{
use Price;
}
} else {
throw new Error('Trait Price not found');
}
} catch (Error $e) {
echo $e->getMessage(); // Output : Trait Price not found
}
为什么第一个例子中的Fatal Error
没有被抓住?
我在第二个例子中的方法是唯一的方法吗?
简短回答:并非所有错误都可以捕获,有些仍然会升级到新的错误/异常模型。
PHP 7.0允许您捕获创建缺少的类:
$foo = new NotAClass;
PHP 7.3将允许您捕获有关不存在的父类的错误(请参阅bug #75765):
class Foo extends NotAClass {}
但是,你仍然无法捕捉到遗失的特征(there's a note on the Github issue for the above bug about this being harder to fix):
class Foo { use NotATrait; }
注意:HHVM显然很好地捕获了所有这些,因为它并不关心你对规则的看法(部分是因为在完全编译的环境中这种事情要容易得多)。
有关演示,请参阅https://3v4l.org/L0fPA。
是的,正如评论中提到的那样,请尝试而不是依赖于在运行时捕获缺少的类/特征。你应该早一点了解你的类层次结构。