码迷,mamicode.com
首页 > Web开发 > 详细

PHP 可变长度参数列表

时间:2016-10-14 06:46:19      阅读:260      评论:0      收藏:0      [点我收藏+]

标签:

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

<?php
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

<?php
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

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

PHP 可变长度参数列表

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!