简体   繁体   English

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

[英]How to escape function argument which has a default value in PHP?

I need to know how can I escape the arguments which has default values in PHP? 我需要知道如何在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? 如何以正确的方式进行上述函数调用?

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 . 你可以在这里看到。

I hope that in this way you can solved issue. 我希望通过这种方式你可以解决问题。

Using non-scalar types as default values 使用非标量类型作为默认值

function avg($a = null,$b =null) {

    $a = is_null($a) ? 1 : $a;
    $b = is_null($b) ? 2 : $b;

   return $a+$b;
}


echo avg(3,4); // Correct Result: 7

echo avg(2,null); // Expected result: 4

echo avg(null,5); // Expected result: 6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM