Question

Let say i have function:

<?php
function myFunction($param1, $param2, /*0 or more extra args*/) {
  // do something with $param1 & $param2
  $args = func_get_args();
  $other_args = array_slice($args, 2); // get the dynamic args
  // do something with $other_args
}
?>

this enables to call:

<?php
myFunction($param1, $param2); // or
myFunction($param1, $param2, $param3); // or
myFunction($param1, $param2, $param3, $param4);
?>

But i want to know if it possible to to take an array of args and pass them into the function e.g:

<?php
$extra_args = array($param3, $param4); // this could also be
$extra_args = array($param3, $param4, $param5); // or any length array
?>

i would like to pass them as separate params into my function e.g

<?php
myFunction($param1, $param2 /* other args split up */);
?>

Thanks in advance!

Was it helpful?

Solution

Yeap - call_user_func_array()'.

http://www.php.net/manual/en/function.call-user-func-array.php

Takes two arguments - the function name (as a string - or possibly, in PHP >= 5.3, an anonymous function, not sure) and an array of params.

Or for methods, forward_static_call_array()

http://www.php.net/manual/en/function.forward-static-call-array.php

PHP's answer to JS's function.prototype.apply() :)

OTHER TIPS

call_user_func_array('myFunction', 
    array_merge(
       array($param1,$param2),
       $extra_args));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top