PHP ternary operator vs null coalescing operator

后端 未结 13 1897
南笙
南笙 2020-11-22 15:58

Can someone explain the differences between ternary operator shorthand (?:) and null coalescing operator (??) in PHP?

When do they behave d

13条回答
  •  面向向阳花
    2020-11-22 16:42

    It seems there are pros and cons to using either ?? or ?:. The pro to using ?: is that it evaluates false and null and "" the same. The con is that it reports an E_NOTICE if the preceding argument is null. With ?? the pro is that there is no E_NOTICE, but the con is that it does not evaluate false and null the same. In my experience, I have seen people begin using null and false interchangeably but then they eventually resort to modifying their code to be consistent with using either null or false, but not both. An alternative is to create a more elaborate ternary condition: (isset($something) or !$something) ? $something : $something_else.

    The following is an example of the difference of using the ?? operator using both null and false:

    $false = null;
    $var = $false ?? "true";
    echo $var . "---
    ";//returns: true--- $false = false; $var = $false ?? "true"; echo $var . "---
    "; //returns: ---

    By elaborating on the ternary operator however, we can make a false or empty string "" behave as if it were a null without throwing an e_notice:

    $false = null;
    $var = (isset($false) or !$false) ? $false : "true";
    echo $var . "---
    ";//returns: --- $false = false; $var = (isset($false) or !$false) ? $false : "true"; echo $var . "---
    ";//returns: --- $false = ""; $var = (isset($false) or !$false) ? $false : "true"; echo $var . "---
    ";//returns: --- $false = true; $var = (isset($false) or !$false) ? $false : "true"; echo $var . "---
    ";//returns: 1---

    Personally, I think it would be really nice if a future rev of PHP included another new operator: :? that replaced the above syntax. ie: // $var = $false :? "true"; That syntax would evaluate null, false, and "" equally and not throw an E_NOTICE...

提交回复
热议问题