三 DOTS 作为 Splat Operator (...) (自 PHP 5.6 以来)
PHP 有一个操作员“......(三点)被称为Splat操作员,它被用来通过一个函数中的参数的任意数量,这种函数被称为变量函数。
例子1:
<?php
function calculateNumbers(...$params){
$total = 0;
foreach($params as $v){
$total = $total + $v;
}
return $total;
}
echo calculateNumbers(10, 20, 30, 40, 50);
//Output 150
?>
计算的每个论点 数字() 函数通过 $params 作为一个序列,当使用 "... ".
有很多不同的方式使用“......”运营商,以下是几个例子:
例子2:
<?php
function calculateNumbers($no1, $no2, $no3, $no4, $no5){
$total = $no1 + $no2 + $no3 + $no4 + $no5;
return $total;
}
$numbers = array(10, 20, 30, 40, 50);
echo calculateNumbers(...$numbers);
//Output 150
?>
例子3:
<?php
function calculateNumbers(...$params){
$total = 0;
foreach($params as $v){
$total = $total + $v;
}
return $total;
}
$no1 = 70;
$numbers = array(10, 20, 30, 40, 50);
echo calculateNumbers($no1, ...$numbers);
//Output 220
?>
例子4:
<?php
function calculateNumbers(...$params){
$total = 0;
foreach($params as $v){
$total = $total + $v;
}
return $total;
}
$numbers1 = array(10, 20, 30, 40, 50);
$numbers2 = array(100, 200, 300, 400, 500);
echo calculateNumbers(...$numbers1, ...$numbers2);
//Output 1650
?>
值得注意的是,变量参数不能用所谓的论点瞄准。
例子5:
<?php
function sumIntegers(int ...$params): int {
$sum = 0;
foreach($params as $value){
$sum += $value;
}
return $sum;
}
echo sumIntegers(params: [1, 2, 3, 4]);
// $params will be equal to ['params' => [1, 2, 3, 4]] in sumIntegers
// throws TypeError sumIntegers(): Argument #1 must be of type int, array given
echo sumIntegers(arbitrary_name: 1, another_name: 2);
// $params will be equal to ['arbitrary_name' => 1, 'another_name' => 2] in sumIntegers
// Outputs: 3
?>
使用未包装的连接序列作为函数呼叫的参数具有相同的效果,如使用每个关键值对作为一个名为论点的函数呼叫。
例子6:
<?php
function fullName(string $first_name, ?string $middle_name = null, ?string $last_name = null): string {
return trim("$first_name|$middle_name|$last_name");
}
$params = ['first_name' => 'John', 'last_name' => 'Doe'];
echo fullName(...$params);
// same as fullName(first_name: 'John', last_name: 'Doe')
// outputs 'John||Doe'
?>
它可以用来将命名的论点转移到某种东西,如一个无缝函数呼叫或一个班级。
例子7:
<?php
function throw_exception(string $exception, ...$parameters) {
throw new $exception(...$parameters);
}
throw_exception(exception: 'Exception', code: 123);
// executes throw new Exception(...['code' => 123])
// which is the same as throw new Exception(code: 123);
?>