PHP8: Null safe operator 

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.

Author: Danyal
I'm skilled programmer with expertise in Vue.js/Nux.js for front-end development and PHP Laravel for back-end development. I excel in building APIs and services, and also have experience in web server setup & maintenance. My versatile skill set allows you to develop and maintain web applications effectively, from the user interface to the server-side functionality. I love coding with never ending learning attitude, thanks for visiting danya.dk