2013-07-11 67 views
1

我有,可以採取可變數目的參數的PHP函數(我用func_get_args()來處理它們)PHP函數 - 調用自與相同(可變數量)參數

class Test { 

    private $ting = FALSE; 

    public function test() { 
     $args = func_get_args(); 
     if ($this->ting) { 
      var_dump($args); 
     } else { 
      $this->ting = TRUE; 
      $this->test($args); //I want to call the function again using the same arguments. (this is pseudo-code) 
     } 
    } 

} 

此功能是不是遞歸( 「$ ting」變量阻止它多次出現)。

我想讓test()使用它給出的相同參數來調用自己。因此,例如: Test->test("a", "b", "c");將輸出如下:

array(3) { [0]=> string(1) "a" [1]=> string(1) "b" [2]=> string(1) "c" }

回答

0

使用call_user_func_array

例子:

class TestClass { 

    private $ting = FALSE; 

    public function test() { 
     $args = func_get_args(); 
     if ($this->ting) { 
      var_dump($args); 
     } else { 
      $this->ting = TRUE; 
      call_user_func_array(array($this, 'test'),$args); 
     } 
    } 

} 

$test = new TestClass(); 

//Outputs array(3) { [0]=> string(6) "apples" [1]=> string(7) "oranges" [2]=> string(5) "pears" } 
$test->test("apples","oranges","pears"); 
+0

爲什麼'&$ this'而不只是'$ this'? – fruitcup

+0

個人喜好。無論哪種方式將工作。 – maxton

1

對於任何人誰是尋找只是一個簡單的答案,在標題的問題,這將調用當前類方法與傳遞給它的是相同的參數:

call_user_func_array([ $this, __FUNCTION__ ], func_get_args()); 

或者,如果它是一個簡單的函數(不是類內的方法),你可以這樣做:

call_user_func_array(__FUNCTION__, func_get_args()); 
相關問題