可变数量的参数列表
PHP 在用户自定义函数中支持可变数量的参数列表。在 PHP 5.6 及以上的版本中,由 ... 语法实现;在 PHP 5.5 及更早版本中,使用函数 func_num_args(),func_get_arg(),和 func_get_args() 。
... in PHP 5.6+
In PHP 5.6 and later, argument lists may include the ... token to denote that the function accepts a variable number of arguments. The arguments will be passed into the given variable as an array; for example:
翻译:在PHP 5.6及更高版本中,参数列表可能包含...标记,表示该函数接受可变数量的参数。 参数将作为数组传递给给定变量; 例如:
Example #13 Using ... to access variable arguments
<?php
function sum(...$numbers) {
$acc = 0;
foreach ($numbers as $n) {
$acc += $n;
}
return $acc;
}
echo sum(1, 2, 3, 4);
?>
以上例程会输出:
10
You can also use ... when calling functions to unpack an array or Traversable variable or literal into the argument list:
翻译:您还可以使用...在调用函数时将数组或Traversable变量或文字解包到参数列表中:
Example #14 Using ... to provide arguments
<?php
function add($a, $b) {
return $a + $b;
}
echo add(...[1, 2])."\n";
$a = [1, 2];
echo add(...$a);
?>
以上例程会输出:
3 3
You may specify normal positional arguments before the ... token. In this case, only the trailing arguments that don't match a positional argument will be added to the array generated by ....
It is also possible to add a type hint before the ... token. If this is present, then all arguments captured by ... must be objects of the hinted class.
翻译:
您可以在...标记之前指定正常的位置参数。 在这种情况下,只有与位置参数不匹配的尾随参数将被添加到由....生成的数组中。
也可以在...令牌之前添加类型提示。 如果存在,则由...捕获的所有参数必须是提示类的对象。
节选自PHP官方文档 和 谷歌翻译。