Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a PHP function that can take a variable number of arguments (and I use func_get_args() to process them)

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

}

This function is not recursive (the "$ting" variable prevents it from going more than once).

I want test() to call itself using the same arguments it was given. So for example: Test->test("a", "b", "c"); would output the following:

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

share|improve this question
add comment

3 Answers

I think you want to use call_user_func_array(); it takes a callable and an array of arguments.

call_user_func_array(array($this, 'test'), $args);

And then calls the function like:

test($args[0], $args[1], ...)

The first parameter is a reference to an object method in the shape of an array of two elements; the first being the object, the second a method name.

Btw, this won't work for private methods because the call context of call_user_func_array() is outside of your object.

share|improve this answer
add comment

Use call_user_func_array.

Example:

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");
share|improve this answer
    
why &$this rather than just $this? –  DrAgonmoray Jul 11 '13 at 23:36
    
Personal preference. Either way will work. –  maxton Jul 11 '13 at 23:39
add comment
while($this -> ting == TRUE){
$this -> test($args);
}
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.