在PHP中,有没有办法使用任意参数从父类调用方法call_user_func_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?
}
Run Code Online (Sandbox Code Playgroud)
这是一个奇怪的黑客?是啊.不过,我会在很多地方使用这个样板文件,在正确转录方法args时可能会出错,所以权衡是为了减少整体错误.
Den*_*huk 27
尝试其中之一
call_user_func_array(array($this, 'parent::' . __FUNCTION__), $args);
Run Code Online (Sandbox Code Playgroud)
要么
call_user_func_array(array('parent', __FUNCTION__), $args);
Run Code Online (Sandbox Code Playgroud)
...取决于您的PHP版本.老年人往往会轻微崩溃,小心:)
Kri*_*ris -2
您可以调用父类上的任何方法,只要该方法没有在靠近实例的类处重载即可。只需使用$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);
Run Code Online (Sandbox Code Playgroud)
MathStuff::multiply基本上,这会在方法查找表中查找方法,并对DangerousCode实例中的实例数据执行其代码。
| 归档时间: |
|
| 查看次数: |
4727 次 |
| 最近记录: |