Unlimited arguments for PHP function?

房东的猫 提交于 2019-12-28 15:43:21

问题


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:


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.




回答2:


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.




回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/5009382/unlimited-arguments-for-php-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!