我正在尝试在我的一个类中实现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的实例被赋予...
我可否知道是否有可能发现该错误(因为它说“可捕捉”)?如果是,如何处理?
发布于 2018-03-19 20:32:19
<?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.
https://stackoverflow.com/questions/-100007674
复制相似问题