How can I use "Nullsafe operator" in PHP

1.3k Views Asked by At

Is there a way to use Nullsafe operator conditions in php?

2

There are 2 best solutions below

3
On BEST ANSWER

PHP 7

$country =  null;

if ($session !== null) {
  $user = $session->user;

  if ($user !== null) {
    $address = $user->getAddress();
 
    if ($address !== null) {
      $country = $address->country;
    }
  }
}

PHP 8

$country = $session?->user?->getAddress()?->country;

Instead of null check conditions, you can now use a chain of calls with the new nullsafe operator. When the evaluation of one element in the chain fails, the execution of the entire chain aborts and the entire chain evaluates to null.

source: https://www.php.net/releases/8.0/en.php

4
On

Nullsafe operator allows you to chain the calls avoiding checking whether every part of chain is not null (methods or properties of null variables).

PHP 8.0

$city = $user?->getAddress()?->city

Before PHP 8.0

$city = null;
if($user !== null) {
    $address = $user->getAddress();
    if($address !== null) {
        $city = $address->city;
    }
}

With null coalescing operator (it doesn't work with methods):

$city = null;
if($user !== null) {
    $city = $user->getAddress()->city ?? null;
}

Nullsafe operator suppresses errors:

Warning: Attempt to read property "city" on null in Fatal error:

Uncaught Error: Call to a member function getAddress() on null

However it doesn't work with array keys:

$user['admin']?->getAddress()?->city //Warning: Trying to access array offset on value of type null

$user = [];
$user['admin']?->getAddress()?->city //Warning: Undefined array key "admin"