Search code examples
phpfunctionmagic-methods

Call a method of a class through another class property using the __call method


I want to call a method ( the method name is dynamically deciding) of a class through another class property using the __call method. I tried as given below. I hope the code will describe what I tried.

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);

But getting the erro.

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

Solution

  • This should solve your problem:

    return call_user_func_array(array($this->a, $name), $args);