Unlimited arguments for PHP function? [duplicate]
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...)
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.
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.
Is there a reason why you couldn't use 1 function argument and pass all the info through as an array?
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.
精彩评论