如何在PHP类型提示上捕获“可捕获的致命错误”?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (10)

我正在尝试在我的一个类中实现PHP5的Type Hinting,

class ClassA {
    public function method_a (ClassB $b)
    {}
}

class ClassB {}
class ClassWrong{}

正确的用法:

$a = new ClassA;
$a->method_a(new ClassB);

产生错误:

$a = new ClassA;
$a->method_a(new ClassWrong);

可捕获致命错误:传递给ClassA :: method_a()的参数1必须是ClassB的实例,ClassWrong的实例被赋予...

我可否知道是否有可能发现该错误(因为它说“可捕捉”)?如果是,如何处理?

提问于
用户回答回答于

<?php
class ClassA {
  public function method_a (ClassB $b) { echo 'method_a: ', get_class($b), PHP_EOL; }
}
class ClassWrong{}
class ClassB{}
class ClassC extends ClassB {}


foreach( array('ClassA', 'ClassWrong', 'ClassB', 'ClassC') as $cn ) {
    try{
      $a = new ClassA;
      $a->method_a(new $cn);
    }
    catch(Error $err) {
      echo "catched: ", $err->getMessage(), PHP_EOL;
    }
}
echo 'done.';

catched: Argument 1 passed to ClassA::method_a() must be an instance of ClassB, instance of ClassA given, called in [...]
catched: Argument 1 passed to ClassA::method_a() must be an instance of ClassB, instance of ClassWrong given, called in [...]
method_a: ClassB
method_a: ClassC
done.

扫码关注云+社区