2010-09-15 107 views
1

我在搜索如何僞造PHP中的多繼承(因爲PHP不直接支持多繼承)時發現此問題。PHP - 僞造的多繼承 - 如何將多個參數傳遞給函數

Can I extend a class using more than 1 class in PHP?

這裏是給有完整的代碼: -

class B { 
    public function method_from_b($s) { 
     echo $s; 
    } 
} 

class C { 
    public function method_from_c($s) { 
     echo $s; 
    } 
} 

class A extends B 
{ 
    private $c; 

    public function __construct() 
    { 
    $this->c = new C; 
    } 

    // fake "extends C" using magic function 
    public function __call($method, $args) 
    { 
    $this->c->$method($args[0]); 
    } 
} 


$a = new A; 
$a->method_from_b("abc"); 
$a->method_from_c("def"); 

問題
這裏給出的例子只考慮一個功能C::method_from_c($s)參數。它正常工作的一個參數,但我有幾個功能class C,有一部分具有2,一些具有3個參數是這樣的: -

class C { 
    public function method_from_c($one,$two) { 
     return $someValue; 
    } 

    public function another_method_from_c($one,$two, $three) { 
     return $someValue; 
    } 
} 

想在C類的函數定義去改變什麼(它必須接受那些許多參數)。例如。我不希望使用func_get_args()我C::method_from_c($s,$two)像這裏面的: -

public function method_from_c() 
{ 

    $args = func_get_args(); 

    //extract params from $args and then treat each parameter 
} 

什麼的__call()功能class A使其作品裏面做。我希望能夠調用Class C功能,如$obj->method_from_c($one,$two);

感謝
Sandeepan

回答

3

您可以使用call_user_func_array

function __call($method, $args) { 
    call_user_func_array(array(&$this->c, $method), $args); 
} 

注意,這雖然不會執行,以及。

+0

$ this-> c的引用運算符是多餘的 – symcbean 2010-09-15 13:13:28

+0

謝謝!有效!!爲什麼它表現不佳? – 2010-09-15 13:18:09

+0

@sandeepan:實際上我不確定,但我依稀記得在某處讀過$ foo - > $ bar()比使用call_user_func更好。 – 2010-09-15 13:29:14

1

你可以在manual找到答案?

public function __call($method_name, $args) 
{ 
    return call_user_method_array($method_name, $this->c, $args); 
} 
+0

拉烏爾公爵的回答比我的好 - (call_user_method fns已棄用) – symcbean 2010-09-15 13:11:49

+0

也爲你+1! – 2010-09-15 13:18:49

相關問題