使用__call方法通过另一个类属性调用类的方法

Hab*_*wad 1 php function magic-methods

我想使用__call方法通过另一个类属性调用类的方法(方法名称是动态决定的).我尝试如下.我希望代码能描述我的尝试.

class A { 

    public function a1($r1) { return 'a1.'; }

    public function a2($r1, $r2) { return 'a2.'; }

    //...
}


class B { 

    private $a; 

    function __construct() { $this->a = new A(); }

    function __call($name, $args) {

        // some code goes here.

        // How to call the method of class-A using the property a.
        return call_user_func_array('$this->a->'.$name, $args);
    }   
}


$b = new B();

// I want to call a1 and a2 of class-A through class-B.
echo $b->a1(11);
echo $b->a2(21, 22);
Run Code Online (Sandbox Code Playgroud)

但得到了错误.

PHP Warning:  call_user_func_array() expects parameter 1 to be a valid callback,
function '$this->a->a2' not found or invalid function name in ...php on line 24
Run Code Online (Sandbox Code Playgroud)

axe*_*hel 5

这应该可以解决您的问题:

return call_user_func_array(array($this->a, $name), $args);
Run Code Online (Sandbox Code Playgroud)