PHP NULL-Safe Operator

PHP 8 introduced a new operator, called “Null-Safe Operator”.

It allows for checking if a method or variable returns null, but doesn’t throw an error.

Can be used in method chaining by returning as soon as it finds a null returned value from any of the methods.

class A{
  public function b(){
    return 'Hello World';
    }
}

Instead of:

$returnValue = null;

$a = new A;

if ($a !== null){
  
  if($a->b() !== null){
    $returnValue = 'Not null';
    }
 }

Can be written as:

$a = new A;

$returnValue = $a?->b() ? 'Not Null' : null;

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *