我将如何确保在调用之前被覆盖的父方法存在?
我试过这个:
public function func() {
if (function_exists('parent::func')) {
return parent::func();
}
}
但是 function_exists 永远不会计算为 true。
最佳答案
public function func()
{
if (is_callable('parent::func')) {
parent::func();
}
}
如果存在,我用它来调用父构造函数,工作正常。
我还使用以下作为通用版本:
public static function callParentMethod(
$object,
$class,
$methodName,
array $args = []
) {
$parentClass = get_parent_class($class);
while ($parentClass) {
if (method_exists($parentClass, $methodName)) {
$parentMethod = new \ReflectionMethod($parentClass, $methodName);
return $parentMethod->invokeArgs($object, $args);
}
$parentClass = get_parent_class($parentClass);
}
}
像这样使用它:
callParentMethod($this, __CLASS__, __FUNCTION__, func_get_args());
关于php - 在调用它之前检查是否存在被覆盖的父方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3046654/