PHP...运算符的用法

作者: 怀老师 | 来源:发表于2020-08-10 19:53 被阅读0次

使用 ... 运算符定义变长参数函数

现在可以不依赖 func_get_args(), 使用 ... 运算符 来实现 变长参数函数

 function f($req, $opt = null, ...$params) {
    // $params 是一个包含了剩余参数的数组
    printf('$req: %d; $opt: %d; number of params: %d'."\n",
           $req, $opt, count($params));
}
 f(1);
 f(1, 2); 
f(1, 2, 3);
 f(1, 2, 3, 4); 
f(1, 2, 3, 4, 5); 

以上例程会输出:

req: 1;opt: 0; number of params: 0
req: 1;opt: 2; number of params: 0
req: 1;opt: 2; number of params: 1
req: 1;opt: 2; number of params: 2
req: 1;opt: 2; number of params: 3

使用 ... 运算符进行参数展开

在调用函数的时候,使用 ... 运算符, 将 数组可遍历 对象展开为函数参数。 在其他编程语言,比如 Ruby中,这被称为连接运算符,。

<?php function add($a, $b, $c) {
    return $a + $b + $c;
}
$operators = [2, 3];
echo add(1, ...$operators); 

以上例程会输出:

6

文章摘自PHP官方手册,仅供查阅。

相关文章

网友评论

    本文标题:PHP...运算符的用法

    本文链接:https://www.haomeiwen.com/subject/lbmbrktx.html