php可变长度参数,PHP 可变长度参数列表

In PHP 5.6 and later, argument lists may include the ... token to denote that the function accepts a variable number of arguments. The arguments will be passed into the given variable as an array; for example:

Example #13 Using ... to access variable arguments

function sum(...$numbers) {

$acc = 0;

foreach ($numbers as $n) {

$acc += $n;

}

return $acc;

}

echo sum(1, 2, 3, 4);

?>

以上例程会输出:

10

You can also use ... when calling functions to unpack an array or Traversable variable or literal into the argument list:

Example #14 Using ... to provide arguments

function add($a, $b) {

return $a + $b;

}

echo add(...[1, 2])."\n";

$a = [1, 2];

echo add(...$a);

?>

以上例程会输出:

3

3

You may specify normal positional arguments before the ... token. In this case, only the trailing arguments(这是什么鬼?) that don‘t match a positional argument will 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

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);

?>

原文:http://www.cnblogs.com/mysic/p/5958739.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值