9

In php how would you create a function that could take an unlimited number of parameters: myFunc($p1, $p2, $p3, $p4, $p5...);

My next question is: how would you pass them into another function something like

function myFunc($params){
  anotherFunc($params);
}

but the anotherFunc would receive them as if it was called using anotherFunc($p1, $p2, $p3, $p4, $p5...)

1

4 Answers 4

13
call_user_func_array('anotherFunc', func_get_args());

func_get_args returns an array containing all arguments passed to the function it was called from, and call_user_func_array calls a given function, passing it an array of arguments.

1
  • 1
    +1 func_get_args exists for exactly the situation where you need to pass an arbitrary number of arguments.
    – Endophage
    Feb 15, 2011 at 21:03
4

Previously you should have used func_get_args(), but in a new php 5.6 (currently in beta), you can use ... operator instead of using .

So for example you can write :

function myFunc(...$el){
  var_dump($el); 
}

and $el will have all the elements you will pass.

2

Is there a reason why you couldn't use 1 function argument and pass all the info through as an array?

1
  • because this is actually for a function in a loader class, you call load::library('name', $p1, $p2, $p3, $p4); it returns a reference to the new class where $p1... is passed to the constructor
    – Hailwood
    Feb 15, 2011 at 21:30
0

Check out the documentation for variable-length argument lists for PHP.

The second part of your question refers to variable functions:

...if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it.

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