【问题标题】:How to catch trait not found error PHP 7如何捕获未找到特征的错误 PHP 7
【发布时间】:2018-08-21 11:08:55
【问题描述】:

从 PHP 7 开始,可以通过捕获 Error 类或 Throwable 接口来捕获 Fatal Errors,但由于某种原因,当“致命错误:未找到特征”被触发时,我无法做到这一点.

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 没有被捕获?

我在第二个例子中的方法是唯一的方法吗?

【问题讨论】:

  • 你为什么要在你的代码中捕捉到它?在尝试使用某个特征之前,您不应该知道它是否存在吗?如果您收到该错误,则您的代码已损坏,您应该确保特征存在或从代码中删除 use

标签: php traits fatal-error


【解决方案1】:

简短回答:并非所有错误都是可捕获的,有些错误仍在升级到新的错误/异常模型。

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 以获取演示。

是的,正如 cmets 中提到的,请尽量不要依赖于在运行时捕获丢失的类/特征。你应该早点知道你的类层次结构方式

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-11
    • 2023-03-25
    • 1970-01-01
    • 2018-09-16
    • 1970-01-01
    • 2018-04-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多