python 在 php 中解压一组参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/294313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
unpacking an array of arguments in php
提问by sgibbons
Python provides the "*" operator for unpacking a list of tuples and giving them to a function as arguments, like so:
Python 提供了“*”运算符来解包元组列表并将它们作为参数提供给函数,如下所示:
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?
有谁知道是否有办法在 PHP 中实现这一点?一些“PHP Unpack”变体的谷歌搜索并没有立即发现任何东西......也许它在PHP中被称为不同的东西?
采纳答案by Greg
You can use call_user_func_array()
to achieve that:
您可以使用以下方法call_user_func_array()
来实现:
call_user_func_array("range", $args);
to use your example.
call_user_func_array("range", $args);
使用你的例子。
回答by Salvador Dali
In php5.6
the ...
operatorhas been added. Using it, you can get rid of call_user_func_array()
for this simpler alternative. For example having a function
在php5.6
该...
运营商已经加入。使用它,您可以摆脱call_user_func_array()
这种更简单的选择。例如有一个功能
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 ...
:
和你的数组$list = [4, 6];
(在 php5.5 之后你可以用这种方式声明数组)。您可以使用以下命令调用您的函数...
:
echo add(...$list);
echo add(...$list);
回答by Oleg Belousov
In certain scenarios, you might consider using unpacking
, which is possible in php, is a similar way to python:
在某些情况下,您可能会考虑使用unpacking
,这在 php 中是可能的,与 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
至少我是这样得出这个答案的。谷歌搜索:PHP argument unpacking
回答by andy.gurin
You should use the call_user_func_array
你应该使用 call_user_func_array
call_user_func_array(array(CLASS, METHOD), array(arg1, arg2, ....))
http://www.php.net/call_user_func_array
http://www.php.net/call_user_func_array
or use the reflection api http://www.php.net/oop5.reflection
或使用反射 api http://www.php.net/oop5.reflection
回答by lov3catch
<?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
另一个例子是 ... - 运算符。
RFC:https: //wiki.php.net/rfc/variadics