转阵成独立的函数参数 - HOWTO? [英] Turn array into independent function arguments - howto?
问题描述
我想在一个数组作为函数调用的参数独立使用的值。例如:
I want to use values in an array as independent arguments in a function call. Example:
// Values "a" and "b"
$arr = array("alpha", "beta");
// ... are to be inserted as $a and $b.
my_func($a, $b)
function my_func($a,$b=NULL) { echo "{$a} - {$b}"; }
值的数组中的数量是未知的。
The number of values in the array are unknown.
可能的解决方案:
-
我可以通过数组作为一个参数 - 但将preFER通过为多个独立的函数参数
I can pass the array as a single argument - but would prefer to pass as multiple, independent function arguments.
破灭()
数组到逗号分隔的字符串。 (失败,因为它只是一个字符串)。
implode()
the array into a comma-separated string. (Fails because it's just one string.)
使用一个参数:
$str = "'a','b'";
function goat($str); // $str needs to be parsed as two independent values/variables.
使用的eval()
?
遍历数组?
建议是AP preciated。谢谢你。
Suggestions are appreciated. Thanks.
推荐答案
这个问题是相当老,但有这个最后更直接的支持PHP 5.6 +
This question is fairly old but there is finally more direct support for this in PHP 5.6+:
的http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list.new
$arr = array("alpha", "beta");
my_func(...$arr);
这篇关于转阵成独立的函数参数 - HOWTO?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!