unpacking an array of arguments in php

泄露秘密 提交于 2019-12-20 11:14:15

问题


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)            # call with arguments unpacked from a list

This is equivalent to:

range(3, 6)

Does anyone know if there is a way to achieve this in PHP? Some googling for variations of "PHP Unpack" hasn't immediately turned up anything.. perhaps it's called something different in PHP?


回答1:


You can use call_user_func_array() to achieve that:

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




回答2:


In php5.6 the ... 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;
}

and your array $list = [4, 6]; (after php5.5 you can declare arrays in this way). You can call your function with ...:

echo add(...$list);




回答3:


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




回答4:


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




回答5:


<?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



来源:https://stackoverflow.com/questions/294313/unpacking-an-array-of-arguments-in-php

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