在php5.6以上版本可以使用…语法实现:
参数列表可以包含 …标记,表示该函数接受可变数量的参数。参数将作为数组传递给给定变量。
例子1:使用…访问可变参数
<?php
function sum(...$numbers) {
$acc = 0;
foreach ($numbers as $n) {
$acc += $n;
}
return $acc;
}
echo sum(1, 2, 3, 4);
//会输出:10
<?php
function sum(...$numbers) {
$acc = 0;
foreach ($numbers as $n) {
$acc += $n;
}
return $acc;
}
echo sum(1, 2, 3, 4);
//会输出:10
<?php function sum(...$numbers) { $acc = 0; foreach ($numbers as $n) { $acc += $n; } return $acc; } echo sum(1, 2, 3, 4); //会输出:10
例子2:数组转为参数列表
<?php
function add($a, $b){
echo $a + $b;
}
$args = array(1, 2);
add(...$args);
// 输出3
<?php
function add($a, $b){
echo $a + $b;
}
$args = array(1, 2);
add(...$args);
// 输出3
<?php function add($a, $b){ echo $a + $b; } $args = array(1, 2); add(...$args); // 输出3
例子3: 部分参数指定,其他参数数量不定
unction concatenate($transform, ...$strings) {
$string = '';
foreach($strings as $piece) {
$string .= $piece;
}
return($transform($string));
}
echo concatenate("strtoupper", "I'd ", "like ", 4 + 2, " apples");
unction concatenate($transform, ...$strings) {
$string = '';
foreach($strings as $piece) {
$string .= $piece;
}
return($transform($string));
}
echo concatenate("strtoupper", "I'd ", "like ", 4 + 2, " apples");
unction concatenate($transform, ...$strings) { $string = ''; foreach($strings as $piece) { $string .= $piece; } return($transform($string)); } echo concatenate("strtoupper", "I'd ", "like ", 4 + 2, " apples");