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?
    – Aif
    Jan 24, 2010 at 11:12
  • Nope, it's third party function :(
    – Kirzilla
    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.

4
  • 9
    Beware though, func_get_args cannot be used as parameter to another function! You need a temporary variable to capture the arguments first.
    – fresch
    Jan 24, 2010 at 12:02
  • 2
    @Jordan, take a look at this question: stackoverflow.com/questions/4979507/… Aug 22, 2011 at 23:14
  • 1
    To sum it up, the temporary variable was only needed for PHP < 5.2.
    – kaiser
    Nov 27, 2014 at 3:05
  • 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. May 12, 2021 at 17:14
11

Use call_user_func_array like

call_user_func_array('another_function', func_get_args());
0
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
  • I've checked reflection API, but my OOP PHP is too poor to understand practical side of "reflection API". :(
    – Kirzilla
    Jan 24, 2010 at 17:57
  • Here is the nice url tuxradar.com/practicalphp/16/4/0 that helped me to understand Reflection class.
    – Kirzilla
    Mar 9, 2010 at 23:25
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);
}

Your Answer

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

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