ellipsis (...) PHP token 有两种用途——将它们视为打包一个数组和解包一个数组。这两个目的都适用于函数参数。
打包
定义函数时,如果您需要为函数提供动态数量的变量(即,您不知道在代码中调用该函数时将提供多少参数)使用ellipsis (...) token 来捕获提供给该函数的所有剩余参数到函数块内可访问的数组中。省略号 (...) 捕获的动态参数的数量可以为零或更多。
For example:
// function definition
function sum (...$numbers) { // use ellipsis token when defining function
$acc = 0;
foreach ($numbers as $nn) {
$acc += $nn;
}
return $acc;
}
// call the function
echo sum(1, 2, 3, 4); // provide any number of arguments
> 10
// and again...
echo sum(1, 2, 3, 4, 5);
> 15
// and again...
echo sum();
> 0
在函数实例化中使用打包时,省略号 (...) 会捕获所有剩余参数,即,您仍然可以拥有任意数量的初始、固定(位置)参数:
function sum ($first, $second, ...$remaining_numbers) {
$acc = $first + $second;
foreach ($remaining_numbers as $nn) {
$acc += $nn;
}
return $acc;
}
// call the function
echo sum(1, 2); // provide at least two arguments
> 3
// and again...
echo sum(1, 2, 3, 4); // first two are assigned to fixed arguments, the rest get "packed"
> 10
解压
或者,在调用函数时,如果您提供给该函数的参数先前组合成一个数组,请使用 ellipsis (...) token 将该数组转换为提供给函数的单个参数 - 每个数组元素都分配给相应的函数函数定义中命名的参数变量。
For example:
function add ($aa, $bb, $cc) {
return $aa + $bb + $cc;
}
$arr = [1, 2, 3];
echo add(...$arr); // use ellipsis token when calling function
> 6
$first = 1;
$arr = [2, 3];
echo add($first, ...$arr); // used with positional arguments
> 6
$first = 1;
$arr = [2, 3, 4, 5]; // array can be "oversized"
echo add($first, ...$arr); // remaining elements are ignored
> 6
在使用array functions 操作数组或变量时,解包特别有用。
例如解包array_slice的结果:
function echoTwo ($one, $two) {
echo "$one\n$two";
}
$steaks = array('ribeye', 'kc strip', 't-bone', 'sirloin', 'chuck');
// array_slice returns an array, but ellipsis unpacks it into function arguments
echoTwo(...array_slice($steaks, -2)); // return last two elements in array
> sirloin
> chuck