PHP › PHP 8 Features (Attributes, Enums, Match, Nullsafe Operator)

What is the nullsafe operator introduced in PHP 8, and how does it simplify safely accessing a chain of potentially null properties or methods?

Beginner

Answer

The nullsafe operator, written as a question mark followed by an arrow, lets you safely access a property or call a method on an object that might be null, automatically short circuiting and returning null for the entire chain the moment any link in that chain is null, rather than throwing an error, eliminating the need for a series of nested isset checks or explicit null comparisons that were previously required to safely navigate a chain of potentially missing related objects.
$city = $user?->address?->city;
// Returns null safely if user or address is null, instead of throwing an error
Real-world example A user profile display safely retrieves a user's city using the nullsafe operator, gracefully handling cases where a user has no associated address record at all, without needing several nested conditional checks to avoid an error.

Common follow-ups: How did developers handle this same scenario safely before PHP 8 introduced the nullsafe operator?;Can the nullsafe operator be used when calling a method rather than just accessing a property?