Nullsafe Operator ?->
The nullsafe operator (PHP 8.0) short-circuits a method chain when any intermediate value is null. No more nested if statements or ternary chains just to safely traverse an object graph.
// Before: defensive null checking at every step
$country = null;
if ($user !== null) {
$address = $user->getAddress();
if ($address !== null) {
$city = $address->getCity();
if ($city !== null) {
$country = $city->getCountry();
}
}
}
// After: one clean expression
$country = $user?->getAddress()?->getCity()?->getCountry();
// Works with properties too
$name = $order?->customer?->profile?->displayName ?? 'Guest';
// Works with method calls and array access
$firstTag = $post?->getTags()?->first()?->name;
// Real-world: Eloquent relationships
$managerEmail = $employee
?->department
?->manager
?->email
?? 'no-manager@company.com';
The nullsafe operator composes perfectly with the null coalescing operator (??). Use ?-> to safely traverse, then ?? to provide a default. It's the complete null-handling toolkit in two operators.
Significance: Expressiveness
Null handling is one of the most common sources of both bugs and boilerplate. The nullsafe operator reduces a pyramid of null checks to a single fluent expression, making the happy path and the null path equally readable. Combined with
??, PHP now has best-in-class null handling.