Check if an object is null (Shortest way)

Viewed 1770


I try to check if an object is null.
In Groovy I can check:

System.out.println(object?.object2?.property)

In other words

if(object != null){
    if(object.object2 != null){
        System.out.println(object.object2.property);
    }
}

Now I want the same in PHP
How can I write the same in the shortest way?

object->object2->property

object2 can be null
if I try to get the property of object2 I get a NPE

Thanks for help.

4 Answers

in version 8 of PHP you can use Nullsafe operator as follow:

$prop = object?->object2?->property;
Related