PHP ternary operator vs null coalescing operator

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

    Both are shorthands for longer expressions.

    ?: is short for $a ? $a : $b. This expression will evaluate to $a if $a evaluates to TRUE.

    ?? is short for isset($a) ? $a : $b. This expression will evaluate to $a if $a is set and not null.

    Their use cases overlaps when $a is undefined or null. When $a is undefined ?? will not produce an E_NOTICE, but the results are the same. When $a is null the result is the same.

提交回复
热议问题