简体   繁体   中英

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? 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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