2012-07-16 46 views
2

可能重複:
PHP, how to pass func-get-args values to another function as list of arguments?具有未知數量參數的方法是否可以調用具有未知數量參數的另一種方法?

我有一個基類的方法,可以採取任意數量的參數。此方法需要調用第三方對象的方法,該方法可以使用傳遞給第一個方法的參數獲取任意數量的參數。

我提到它是一個第三方對象,被調用來強化被調用方法的簽名不能被修改爲接受數組或對象的約束。

例子:

<?php 
class Example {  

    private $thirdPartyObject = null; 

    public function methodOne() { 
     $arguments = func_get_args(); 

     $this->thirdPartyObject = new ThirdPartyObject(); 
     $this->externalObject->methodName(/* pass on variable number of arguments here */); 
    } 
} 

$exampleObject = new Example(); 
$exampleObject->methodOne('a', 'b', 'c'); 


如果我們事先知道被傳遞到Example->methodOne()參數的個數,然後我們可以在相同數量的參數傳遞給ThirdPartyObject->methodName()

如果我們事先不知道傳遞給Example->methodOne()的參數的數量,我們可以將這些參數傳遞給ThirdPartyObject->methodName()嗎?

在這種情況下,ThirdPartyObject->methodName()被稱爲與一個或多個參數,如:

<?php 
$thirdPartyObject = new ThirdPartyObject(); 
$thirdPartyObject->methodName('a'); 
$thirdPartyObject->methodName('a', 'b'); 
$thirdPartyObject->methodName('a', /* ... */, 'N'); 
+2

您是否嘗試過這個?:[http://stackoverflow.com/questions/2126778/ph​​p-how-to-pass-func-get-args - 值對另一個功能-AS--的-參數列表(http://stackoverflow.com/questions/2126778/ph​​p-how-to-pass-func-get-args-values-to-another- function-as-list-of-arguments) – Zbigniew 2012-07-16 15:11:38

+0

@des:謝謝你的建議,我的搜索沒有找到它。 – 2012-07-16 15:23:56

回答

0

您可以使用call_user_func_array

但是,您應該簡單地傳遞參數數組($arguments)並將其用於其他方法。

+0

「你應該簡單地傳遞參數數組」 - 另一種方法是第三方對象,它不需要一個參數數組,我不能改變這個, – 2012-07-16 15:20:48

+0

@JonCram:考慮我的第二部分答案沒用,其中案件。如果其他用戶遇到同樣的問題,我會留下以供將來參考,只有他可以更改其代碼的結構。 – 2012-07-16 15:24:01

3

您正在談論call_user_func_array(),我想。但使用它並不是一個好習慣。這很慢。

call_user_func_array(array($this->externalObject, "methodName"), $arguments); 
+0

如果使用諸如APC之類的操作碼緩存,這種性能問題的重要性較低? – 2012-07-16 15:23:14

-1

嘗試使用類示例擴展ThirdPartyObject,然後爲要傳遞的變量設置默認值。

+0

在這種特定情況下,Example是一個Symfony2實體,ThirdPartyObject是Doctrine EntityRepository。這是行不通的。 – 2012-07-16 15:21:50

1

是,使用call_user_func_array(),就像這樣:

$this->thirdPartyObject = new ThirdPartyObject(); 
call_user_func_array(array($this->externalObject, 'methodName'), $arguments); 
相關問題