What Is the Nullsafe Operator in PHP?

Introduced in PHP 8, the nullsafe operator (?->) allows you to call object methods or access object properties within a chain of connected objects where an object in the chain can potentially be null. It has a similar syntax to the property/method access operator (->):

// PHP 8+
$obj->val?->prop
$obj->val?->method()

The expression is evaluated left-to-right, and when/if the left-hand side of the operator evaluates to null, the execution of the entire chain is stopped and evaluated to null. Conversely, when it is not null it behaves exactly like the normal -> operator.

For example, imagine a Person class like so:

class Person
{
    public function getBirthDate(): ?DateTimeInterface
    {
        // ...
    }
}

The return value of the Person::getBirthDate() can potentially be null which makes it a good candidate to use the nullsafe operator if you wish to call a method (or access a property) on the object you're expecting to be returned:

// PHP 8+
var_dump($person->getBirthDate()?->getTimezone());

Here, if Person::getBirthDate() returns null, then the whole expression with the nullsafe operator will short-circuit evaluate to null.

Without the nullsafe operator, for example in prior versions of PHP, you would have had to check if the object was null or not to make it nullsafe (which in some cases would mean a lot of nested checks and repetition):

if ($person->getBirthDate()) {
    var_dump($person->getBirthDate()->getTimezone());
}

If you were to omit those checks altogether, PHP would throw the following error when the returned value is null instead of the object you expect:

// Uncaught Error: Call to a member function getTimezone() on null
$person->getBirthDate()->getTimezone();

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.