简体   繁体   中英

PHP Null coalescing operator usage

Having this example code using the tertiary operator in PHP, I get the 'default value'.

$myObject = null; // I'm doing this for the example
$result = $myObject ? $myObject->path() : 'default value';

However, when I try to use the null coalescing operator to do this, I get the error

Call to a member function path() on null

$result = $myObject->path() ?? 'default value';

What am I doing wrong with the ?? operator?

These snippets do not work in the same way:

$result = $myObject ? $myObject->path() : 'default value'; says: use 'default value' if $myObject is NULL

$result = $myObject->path() ?? 'default value'; says: use the default if $myObject->path() returns NULL - but that call can only return something if the object itself is not NULL

?? will work if the left hand side is null or not set, however in your case the left hand cannot be evaluated if $myObject is null.

What you should consider in your case is the new nullsafe operator available with PHP 8 (so need to wait on that)

$result = $myObject?->path() ?? 'default value';

This should make the left hand side null if $myObject is null

Until then you can just do:

$result = ($myObject ? $myObject->path() : null) ?? 'default value'; 

This differs from your first use case in that you get default value if either $myObject or $myObject->path() are null

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