-1

I have nested objects and method calls like this for an XML web service:

$value = $object->getData()->getSomething()->getValue();

The problem is, if one nested object does not exists, there is an Error thrown like this:

Call to a member function getData() on null 

Can I avoid having silly code like this:

if ($object && $object->getData() && $object->getData()->getSomething()) {
   $value = $object->getData()->getSomething()->getValue();
}

or catching an Error:

try {
   $value = $object->getData()->getSomething()->getValue();
} catch (Error $e) {

}

The best would be something like:

if (isset($object->getData()->getSomething())) {
   $value = $object->getData()->getSomething()->getValue();
}
Sebastian Viereck
  • 5,455
  • 53
  • 53

1 Answers1

0

Starting with PHP 8 it is possible now:

$value = $object?->getData()?->getSomething()?->getValue();

Explanation PHP8 Nullsafe operator:

When the left hand side of the operator evaluates to null the execution of the entire chain will stop and evalute to null.

Sebastian Viereck
  • 5,455
  • 53
  • 53