PHP函数参数前面三个点的作用

最近经常看到项目里面有这种写法,记录一下,方便查看

1
2
3
4
function sum(...$number){
..........
}

详细说明 https://www.php.net/manual/zh/functions.arguments.php#functions.variable-arg-list

举个栗子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function sum(...$input)
{
$total = 0;
array_walk($input, function($v)use(&$total){
$total += $v;
});
return $total;
}
function multiple($arg1, $arg2, $arg3)
{
return $arg1 * $arg2 * $arg3;
}
echo sum(1,2,3,4,5) . PHP_EOL; //15
echo multiple(...[1,2,3]) . PHP_EOL; //6

sum(): 因为实参是多个参数,形参是一个参数,所以 …$input 会将多个实参转换成单个形参,即 $input = [1,2,3,4,5];

multiple():因为实参是单个参数,形参是多个参数,所以 …$input 会将单个实参转换成对应的多个形参,即:

$arg1 = 1、$arg2 = 2、$arg3 = 3;