代码之家  ›  专栏  ›  技术社区  ›  Rain cheladon

如何捕获未找到的trait错误PHP 7

  •  3
  • Rain cheladon  · 技术社区  · 6 年前

    从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 在第一个例子中没有被抓到?

    1 回复  |  直到 6 年前
        1
  •  6
  •   iainn    6 年前

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

    PHP 7.0允许您捕获创建缺少的类:

    $foo = new NotAClass;
    

    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 为了演示。

    方式 在那之前。