zoukankan      html  css  js  c++  java
  • 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

    <?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])." ";

    $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);
    ?>
  • 相关阅读:
    洛谷P3620 [APIO/CTSC 2007] 数据备份
    洛谷P2744 量取牛奶
    洛谷P1560 蜗牛的旅行
    luogu P1776 宝物筛选_NOI导刊2010提高(02)
    luogu P1020 导弹拦截
    luogu P2015 二叉苹果树
    luogu P1137 旅行计划
    树形dp瞎讲+树形dp基础题题解
    luogu P1252 马拉松接力赛 P1803 凌乱的yyy / 线段覆盖
    luogu P1196 [NOI2002]银河英雄传说
  • 原文地址:https://www.cnblogs.com/mysic/p/5958739.html
Copyright © 2011-2022 走看看