Null Safe Operator
4 min read Quiz at the end
The null safe operator ?-> safely calls methods on a value that might be null. If the value is null, the whole chain returns null instead of throwing an error. It replaces long chains of nested null checks.
Null Safe Operator ?-> (PHP 8)
// Before PHP 8 — verbose null checks
$city = null;
if ($user !== null) {
$addr = $user->getAddress();
if ($addr !== null) {
$city = $addr->getCity();
}
}
// PHP 8 — null safe operator
$city = $user?->getAddress()?->getCity();
// Returns null at the first null in the chain
// With array access
$country = $user?->getAddress()?->country;
// Chaining methods
$zip = $order?->getUser()?->getAddress()?->getZip();
// Does NOT short-circuit write operations
// $user?->name = "Alice"; // still an error if $user is null