Unlimited arguments for PHP function?

后端 未结 4 1972
野性不改
野性不改 2020-12-10 05:56

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 w

相关标签:
4条回答
  • 2020-12-10 06:30

    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.

    0 讨论(0)
  • 2020-12-10 06:33

    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.

    0 讨论(0)
  • 2020-12-10 06:35
    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.

    0 讨论(0)
  • 2020-12-10 06:41

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

    0 讨论(0)
提交回复
热议问题