Nullsafe Operator in PHP 8

PHPServer Side ProgrammingProgramming

PHP 8 uses nullsafe operator instead of a null check condition. Using the nullsafe operator, we can use a chain of calls. While evaluating the elements, if one chain element fails, then the execution of the entire chain will abort and it evaluates to null.

When the left-hand side operator evaluates to null, then the whole chain of execution will stop and it evaluates to null. If it does not evaluate to null, then it will behave like a normal operator.

The nullsafe operator can be chained, and the expression will be short-circuited from the first nullsafe operator that meets null.

$employee->getDepartment()?->getAddress()->format();

The nullsafe syntax is like the method/property access operator(→). We use "?→" for null-safe operator.

Syntax: PHP 8 Nullsafe operator

$foo?->bar?->baz;

Example: PHP 8 Nullsafe Operator(?→)

<?php
   class Emp{
      public function getAddress() {}
   }
   $emp = new Emp();
   $dept = $emp?->getAddress()?->dept?->iso_code;
   print_r($dept);
?>

Output

null
raja
Published on 01-Apr-2021 06:33:01
Advertisements