Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a "nullsafe operator" in PHP?

Is there any way to write the following statement using some kind of safe navigation operator?

echo $data->getMyObject() != null ? $data->getMyObject()->getName() : '';

So that it looks like this:

echo $data->getMyObject()?->getName();
like image 783
Dennis Avatar asked Sep 10 '12 12:09

Dennis


2 Answers

From PHP 8, you are able to use the null safe operator which combined with the null coalescing operator allows you to write code like:

echo $data->getMyObject()?->getName() ?? '';

By using ?-> instead of -> the chain of operators is terminated and the result will be null.

The operators that "look inside an object" are considered part of the chain.

  • Array access ([])
  • Property access (->)
  • Nullsafe property access (?->)
  • Static property access (::)
  • Method call (->)
  • Nullsafe method call (?->)
  • Static method call (::)

e.g. for the code:

$string = $data?->getObject()->getName() . " after";

if $data is null, that code would be equivalent to:

$string = null . " after";

As the string concatenation operator is not part of the 'chain' and so isn't short-circuited.

like image 174
Danack Avatar answered Sep 30 '22 23:09

Danack


No there is not.

The absolute best way to deal with this is to design your objects in a way that they always return a known, good, defined value of a specific type.

For situations where this is absolutely not possible, you'll have to do:

$foo = $data->getMyObject();
if ($foo) {
    echo $foo->getName();
}

or maybe

echo ($foo = $data->getMyObject()) ? $foo->getName() : null;
like image 27
deceze Avatar answered Oct 01 '22 01:10

deceze