PHP 可变长度参数列表
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP 可变长度参数列表相关的知识,希望对你有一定的参考价值。
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:
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:
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.
Example #15 Type hinted variable arguments
<?php
function total_intervals($unit, DateInterval ...$intervals) {
$time = 0;
foreach ($intervals as $interval) {
$time += $interval->$unit;
}
return $time;
}
$a = new DateInterval(‘P1D‘);
$b = new DateInterval(‘P2D‘);
echo total_intervals(‘d‘, $a, $b).‘ days‘;
// This will fail, since null isn‘t a DateInterval object.
echo total_intervals(‘d‘, null);
?>
以上是关于PHP 可变长度参数列表的主要内容,如果未能解决你的问题,请参考以下文章