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);
    ?>
  • 相关阅读:
    RESTful API 介绍,设计
    golang web框架设计7:整合框架
    golang web框架设计6:上下文设计
    golang web框架设计5:配置设计
    golang web框架设计4:日志设计
    golang web框架设计3:controller设计
    golang web框架设计2:自定义路由
    golang web框架设计1:框架规划
    深入理解golang: channels
    服务端高并发分布式十四次架构演进之路
  • 原文地址:https://www.cnblogs.com/mysic/p/5958739.html
Copyright © 2011-2022 走看看