PHP Null coalescing operator usage

2.2k Views Asked by At

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?

2

There are 2 best solutions below

3
On BEST ANSWER

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

1
On

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