dpw43061 2015-07-17 08:35
浏览 25
已采纳

PHP中可变数量的参数[关闭]

In the course of converting some code from Java to PHP, I came across the following Java code:

void doSomething(String requiered, String... optionals) {...}

I know it's possible to create a similar function signature using func_get_args() and I know I could also pass the unknown count of params in an array. However, neither seems straight forward to me, so I was wondering if there might be a better way to have a variable number of arguments in PHP.

  • 写回答

1条回答 默认 最新

  • doufu9145 2015-07-17 08:44
    关注

    PHP 5.6 introduces ability to have this exact construct. From PHP manual:

    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

    <?php
    function sum($acc, ...$numbers) {
        foreach ($numbers as $n) {
            $acc += $n;
        }
        return $acc;
    }
    
    echo sum(1, 2, 3, 4);
    ?>
    

    http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法