unpacking an array of arguments in php

后端 未结 5 1914
醉话见心
醉话见心 2020-12-15 04:11

Python provides the \"*\" operator for unpacking a list of tuples and giving them to a function as arguments, like so:

args = [3, 6]
range(*args)                     


        
相关标签:
5条回答
  • 2020-12-15 04:46

    In php5.6 Argument unpacking via ... (splat operator) has been added. Using it, you can get rid of call_user_func_array() for this simpler alternative. For example having a function:

    function add($a, $b){
      return $a + $b;
    }
    

    With your array $list = [4, 6]; (after php5.5 you can declare arrays in this way).

    You can call your function with ...:

    echo add(...$list);
    
    0 讨论(0)
  • 2020-12-15 04:47

    You should use the call_user_func_array

    call_user_func_array(array(CLASS, METHOD), array(arg1, arg2, ....))
    

    http://www.php.net/call_user_func_array

    or use the reflection api http://www.php.net/oop5.reflection

    0 讨论(0)
  • 2020-12-15 04:56

    In certain scenarios, you might consider using unpacking, which is possible in php, is a similar way to python:

    list($min, $max) = [3, 6];
    range($min, $max);
    

    This is how I have arrived to this answer at least. Google search: PHP argument unpacking

    0 讨论(0)
  • 2020-12-15 05:06

    You can use call_user_func_array() to achieve that:

    call_user_func_array("range", $args); to use your example.

    0 讨论(0)
  • 2020-12-15 05:06
    <?php
    
    function add(int ...$arr) {           // typehint ready
        return array_sum($arr);
    }
    
    var_dump(add(1, 2, 3, ...[1, 2, 3])); // int(12)
    

    Another example with ... - operator.
    RFC: https://wiki.php.net/rfc/variadics

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