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);
    ?>
  • 相关阅读:
    干掉idea视图黄色警告
    idea插件 Background Image Plus 随机更换背景图片
    es的rest风格的api文档
    使用postman对elasticsearch接口调用
    es插件安装
    emoji表情等特殊字符处理和存储的两个方案
    java8两个字段进行排序问题
    java 必应壁纸批量下载
    elasticsearch学习(1)
    RocketMq报错 Java HotSpot(TM) Server VM warning:
  • 原文地址:https://www.cnblogs.com/mysic/p/5958739.html
Copyright © 2011-2022 走看看