Null safe operator is a new short syntax in PHP 8.0, that provides an optional chaining feature to PHP.
The null-safe operator allows reading the value of a property and method, where the null-safe operator short-circuits the retrieval if the value is null
, without any errors.
The syntax is similar to the property/method access operator (->
), and following the nullable type pattern, the null-safe operator is ?->
.
Example of reading chain properties/objects:
null-safe returns null without no errors if the object on the left side is null.
$vehicle?->car
$vehicle?->car?->color
Following the snippet, we are accessing the car color and storing data in the variable $car_color.
In this case, if the vehicle or car is null, a Fatal error will be thrown.
<?php
class Vehicle {
public function getCar(): ?Car {}
}
class Car {
public function getColor(): string {}
}
$vehicle = new Vehicle();
$car_color = $vehicle->getCar()->getColor();
Fatal error: Uncaught Error: Call to a member function getColor() on null in ...:...
To safely access the color, it is necessary to check the null return values before further accessing the return value, for example:
$vehicle = new Vehicle();
if ($vehicle) {
$car = $vehicle->getCar();
$color = $car ? $car->getColor() : null;
} else {
$color = null;
}
But PHP8 provides null-safe operator, that will silently return null. If the object on the left side is null.
$vehicle = new Vehicle();
$color = $vehicle->getCar()?->getColor();
And that’s it, less & an efficient operator, if you decide to refactor your code; remember that is operator is only available in PHP8 or greater versions.