PHP ternary operator vs null coalescing operator

后端 未结 13 1817
南笙
南笙 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:25

    Null Coalescing operator performs just two tasks: it checks whether the variable is set and whether it is null. Have a look at the following example:

    The above code example states that Null Coalescing operator treats a non-existing variable and a variable which is set to NULL in the same way.

    Null Coalescing operator is an improvement over the ternary operator. Have a look at the following code snippet comparing the two:

    So, the difference between the two is that Null Coalescing operator operator is designed to handle undefined variables better than the ternary operator. Whereas, the ternary operator is a shorthand for if-else.

    Null Coalescing operator is not meant to replace ternary operator, but in some use cases like in the above example, it allows you to write clean code with less hassle.

    Credits: http://dwellupper.io/post/6/php7-null-coalescing-operator-usage-and-examples

提交回复
热议问题