1

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!

9
  • What have you tried? You want to call your function with a array of params? Commented Jul 13, 2012 at 18:18
  • yea, that's what i want to do
    – Lizard
    Commented Jul 13, 2012 at 18:20
  • This question seems very basic. Yes, you can pass a param of an array to the function as long as you build the function to handle it.
    – Jeremy
    Commented Jul 13, 2012 at 18:21
  • @Jeremy - he doesn't want to pass an array, he wants to use an array and have it passed as though each element in the array was passed as its own function parameter, like JavaScript's function.prototype.apply() method (if that helps).
    – Mitya
    Commented Jul 13, 2012 at 18:35
  • Why does it have to be called as if all the args were passed as opposed to putting them in an array and handling them that way? I dont see why thats necessary. I do agree that your solution does match what the person is asking though @Utkanos
    – sbditto85
    Commented Jul 13, 2012 at 18:45

2 Answers 2

4

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() :)

1
  • call_user_func_array will probably work for my scenario - can't believe I didn't think of that :) Also didn't know of forward_static_call_array - but unfortunately the function is static - good to know though.
    – Lizard
    Commented Jul 13, 2012 at 18:25
1
call_user_func_array('myFunction', 
    array_merge(
       array($param1,$param2),
       $extra_args));

Your Answer

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

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