36

I want to create a function (my_function()) getting unlimited number of arguments and passing it into another function (call_another_function()).

function my_function() {    
   another_function($arg1, $arg2, $arg3 ... $argN);    
}

So, want to call my_function(1,2,3,4,5) and get calling another_function(1,2,3,4,5)

I know that I shoud use func_get_args() to get all function arguments as array, but I don't know how to pass this arguments to another function.

Thank you.

2
  • Can't you modify another_function to accept an array as parameter? Commented Jan 24, 2010 at 11:12
  • Nope, it's third party function :( Commented Jan 24, 2010 at 17:56

4 Answers 4

56

Try call_user_func_array:

function my_function() {    
    $args = func_get_args();
    call_user_func_array("another_function", $args);
}

In programming and computer science, this is called an apply function.

Sign up to request clarification or add additional context in comments.

4 Comments

Beware though, func_get_args cannot be used as parameter to another function! You need a temporary variable to capture the arguments first.
@Jordan, take a look at this question: stackoverflow.com/questions/4979507/…
To sum it up, the temporary variable was only needed for PHP < 5.2.
The callback seems to be interpreted eval-alike and call_user_func_array also returns the callback's result. $ret_value = call_user_func_array("MyClass::my_method", $args); works.
11

Use call_user_func_array like

call_user_func_array('another_function', func_get_args());

Comments

1

It's not yet documented but you might use reflection API, especially invokeArgs.

(maybe I should have used a comment rather than a full post)

2 Comments

I've checked reflection API, but my OOP PHP is too poor to understand practical side of "reflection API". :(
Here is the nice url tuxradar.com/practicalphp/16/4/0 that helped me to understand Reflection class.
0

I have solved such a problem with the ...$args parameter in the function.

In my case, it was arguments forwarding to the parent construction call.

public function __construct(...$args)
{
    parent::__construct(...$args);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.