如何捕获特征未找到错误 PHP 7
How to catch trait not found error PHP 7
从 PHP 7 开始,可以通过捕获 Error
class 或 Throwable
接口来捕获 Fatal Errors
,但出于某种原因我不能'当 "Fatal Error: trait not found" 被触发时,我无法做到这一点。
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
没有被捕获?
我在第二个例子中的方法是唯一的方法吗?
简短回答:并非所有错误都可以捕获,有些错误仍在升级到新的 error/exception 模型。
PHP 7.0 让你赶上创造缺失 class:
$foo = new NotAClass;
PHP 7.3 将让您捕获有关父 class 不存在的错误(参见 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。
是的,正如评论中提到的,请尝试不要依赖于在 运行 时捕捉缺失的 classes / traits。你应该知道你的 class 层次结构 way 早于那个。
从 PHP 7 开始,可以通过捕获 Error
class 或 Throwable
接口来捕获 Fatal Errors
,但出于某种原因我不能'当 "Fatal Error: trait not found" 被触发时,我无法做到这一点。
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
没有被捕获?
我在第二个例子中的方法是唯一的方法吗?
简短回答:并非所有错误都可以捕获,有些错误仍在升级到新的 error/exception 模型。
PHP 7.0 让你赶上创造缺失 class:
$foo = new NotAClass;
PHP 7.3 将让您捕获有关父 class 不存在的错误(参见 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。
是的,正如评论中提到的,请尝试不要依赖于在 运行 时捕捉缺失的 classes / traits。你应该知道你的 class 层次结构 way 早于那个。