In PHP 5.6 and later, argument lists may include the ... token to denote the function accepts a variable num ber of arguments. The arguments'll be passed to 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);
?>
The above routines will output:
10
can also use ... when calling functions to unpack a array or traversable variable or literal into th E 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);
?>
The above routines will output:
33
You may specify normal positional arguments before the ... token. In this case, only the trailing arguments (what the hell is this?) that don ' t match a positional argument would 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 variable-length parameter list