1

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?

bandejapaisa
  • 26,576
  • 13
  • 94
  • 112

2 Answers2

4

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

apokryfos
  • 38,771
  • 9
  • 70
  • 114
3

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

Nico Haase
  • 11,420
  • 35
  • 43
  • 69
  • Oh ok cool. So I should be able to chain ?? operator. But then if I do that, what's the point, I might as well use the tertiary operator... – bandejapaisa Oct 14 '20 at 08:41
  • That depends on what you want to achieve :) As far as I see, the first code you are using does what it should, and there is no shorter way – Nico Haase Oct 14 '20 at 08:43
  • Yup, thought so... i edited my comment. As you say, there is no shorter way, so what would be the point – bandejapaisa Oct 14 '20 at 08:43