簡體   English   中英

使用__call方法通過另一個類屬性調用一個類的方法

[英]Call a method of a class through another class property using the __call method

我想使用__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);

但是得到錯誤。

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

這應該可以解決您的問題:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM