在PHP中使用call_user_函数访问父方法
在PHP中,是否有任何方法可以使用任意参数在PHP中使用call_user_函数访问父方法,php,polymorphism,Php,Polymorphism,在PHP中,是否有任何方法可以使用任意参数call\u user\u func\u array从父类调用方法?本质上,我想写一点样板代码,虽然稍微不太理想,但可以让我任意调用方法的父级,如下所示: function childFunction($arg1, $arg2, $arg3 = null) { // I do other things to override the parent here... $args = func_get_args(); call_use
call\u user\u func\u array
从父类调用方法?本质上,我想写一点样板代码,虽然稍微不太理想,但可以让我任意调用方法的父级,如下所示:
function childFunction($arg1, $arg2, $arg3 = null) {
// I do other things to override the parent here...
$args = func_get_args();
call_user_func_array(array(parent, __FUNCTION__), $args); // how can I do this?
}
这是一个奇怪的黑客吗?是 啊不过,我将在许多地方使用此样板文件,在这些地方,正确地转录方法args可能会有错误,因此折衷的办法是总体上减少bug。尝试以下任一种方法
call_user_func_array(array($this, 'parent::' . __FUNCTION__), $args);
或
。。。取决于您的PHP版本。较旧的方法往往会发生轻微的崩溃,请小心:)您可以调用父类上的任何方法,只要它没有重载到实例的类附近。只需使用
$this->methodName(…)
对于稍微更高级的魔法,这里有一个您似乎想要的工作示例:
请注意,我认为这不是一个好主意
class MathStuff
{
public function multiply()
{
$total = 1;
$args = func_get_args();
foreach($args as $order => $arg)
{
$total = $total * $arg;
}
return $total;
}
}
class DangerousCode extends MathStuff
{
public function multiply()
{
$args = func_get_args();
$reflector = new ReflectionClass(get_class($this));
$parent = $reflector->getParentClass();
$method = $parent->getMethod('multiply');
return $method->invokeArgs($this, $args);
}
}
$danger = new DangerousCode();
echo $danger->multiply(10, 20, 30, 40);
基本上,它在方法查找表中查找方法
MathStuff::multiply
,并对来自DangerousCode
实例的实例数据执行其代码。我敢打赌,这样的构造更可能导致错误,因为call\u user\u func\u array
和friends有些神奇。有些事情告诉我可能有更好的解决办法,但问题还不清楚,我看不出来。。然而,在较旧的版本中(更新您的系统!),您必须使用第一个方法(array('this,'parent::')。\uuu FUNCTION\uuuu)
),如果您从使用call\u user\u func\u array
调用parent的类进行扩展,将导致无限递归。使用第二种方法,它工作正常。
class MathStuff
{
public function multiply()
{
$total = 1;
$args = func_get_args();
foreach($args as $order => $arg)
{
$total = $total * $arg;
}
return $total;
}
}
class DangerousCode extends MathStuff
{
public function multiply()
{
$args = func_get_args();
$reflector = new ReflectionClass(get_class($this));
$parent = $reflector->getParentClass();
$method = $parent->getMethod('multiply');
return $method->invokeArgs($this, $args);
}
}
$danger = new DangerousCode();
echo $danger->multiply(10, 20, 30, 40);