代码之家  ›  专栏  ›  技术社区  ›  Joe Mastey

在PHP中使用call\u user\u函数访问父方法

  •  9
  • Joe Mastey  · 技术社区  · 14 年前

    在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?
    }
    

    这是一个奇怪的黑客吗?是 啊。不过,我将在许多地方使用这个样板文件,在这些地方,正确地转录方法参数可能会出错,因此总体而言,权衡的办法是减少bug。

    2 回复  |  直到 11 年前
        1
  •  -2
  •   Kris    14 年前

    您可以调用父类上的任何方法,只要它不重载到实例的类附近。只是使用 $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 实例。

        2
  •  30
  •   Denis 'Alpheus' Cahuk    14 年前

    call_user_func_array(array($this, 'parent::' . __FUNCTION__), $args);
    

    call_user_func_array(array('parent', __FUNCTION__), $args);
    

    ... 取决于您的PHP版本。年长的人容易轻微地崩溃,小心:)