Search code examples
phpphp-8

How can I use "Nullsafe operator" in PHP


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


Solution

  • 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