Null-safe operator is a new syntax in PHP 8.0, that provides optional chaining feature to PHP.
In PHP, when working with objects, sometimes a property or method may not exist (it can be null
).
Normally, checking this requires multiple if conditions to avoid errors.
PHP 8 introduced the Nullsafe Operator (?->
) to make this easy.
Old Way (Before PHP 8)
<?php
if ($student !== null) {
if ($student->address !== null) {
echo $student->address->city;
}
}
?>
We need multiple if
checks to avoid “Trying to get property of non-object” error.
New Way in PHP 8 (Nullsafe Operator)
<?php
echo $student?->address?->city;
?>
If $student
is null
, or $student->address
is null
, the expression will not throw an error. It will simply return null
.
Real-Life Example
<?php
class Student {
public function __construct(
public string $name,
public ?Address $address = null
) {}
}
class Address {
public function __construct(
public string $city
) {}
}
$student1 = new Student("Amit", new Address("Delhi"));
$student2 = new Student("Rahul"); // No address
echo $student1?->address?->city; // Delhi
echo $student2?->address?->city; // null (No error!)
?>
Without nullsafe, $student2->address->city
would crash.
With nullsafe, it just gives null
safely.
Benefits of Nullsafe Operator
- No need to write nested
if
checks - Prevents runtime errors
- Makes code short, clean, and safe
In short: The Nullsafe Operator ?->
in PHP 8 helps you safely access object properties/methods without worrying about null
errors.