doufu1950 2019-04-30 06:03
浏览 106

如何在PHP中转义具有默认值的函数参数?

I need to know how can I escape the arguments which has default values in PHP? Imagine my function is:

function avg($a = 1 , $b = 2) {
   return $a+$b;
}

and I want to call it in these forms:

avg(3,4); // Correct Result: 7
avg(2); // Expected result: 4
avg(,5) // Expected result: 6

How can I do the function calls above in a correct way?

  • 写回答

2条回答 默认 最新

  • douyong1885 2019-04-30 06:20
    关注

    But you can Do this,

    function avg(...$args)
    {
        list($a, $b) = $args + [1, 2];
        $a           = !empty($a) ? $a : 1;
        return $a + $b;
    }
    print_r(avg(3, 4)); // Correct Result: 7
    print_r(avg(2)); // Expected result: 4
    print_r(avg(null, 5)); // Expected result: 6
    

    Demo.

    It's not possible to skip arguments you did that way. You can achieve that only if they are at the end of the parameter's list.

    There has been already many proposals sent in this regards but sadly rejected from there end.

    You can see those here.

    评论

报告相同问题?

悬赏问题

  • ¥50 comsol稳态求解器 找不到解,奇异矩阵有1个空方程返回的解不收敛。没有返回所有参数步长;pid控制
  • ¥15 怎么让wx群机器人发送音乐
  • ¥15 fesafe材料库问题
  • ¥35 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功