
- PHP 7 Tutorial
- PHP 7 - Home
- PHP 7 - Introduction
- PHP 7 - Performance
- PHP 7 - Environment Setup
- PHP 7 - Scalar Type Declarations
- PHP 7 - Return Type Declarations
- PHP 7 - Null Coalescing Operator
- PHP 7 - Spaceship Operator
- PHP 7 - Constant Arrays
- PHP 7 - Anonymous Classes
- PHP 7 - Closure::call()
- PHP 7 - Filtered unserialize()
- PHP 7 - IntlChar
- PHP 7 - CSPRNG
- PHP 7 - Expectations
- PHP 7 - use Statement
- PHP 7 - Error Handling
- PHP 7 - Integer Division
- PHP 7 - Session Options
- PHP 7 - Deprecated Features
- PHP 7 - Removed Extensions & SAPIs
- PHP 7 Useful Resources
- PHP 7 - Quick Guide
- PHP 7 - Useful Resources
- PHP 7 - Discussion
Nullsafe Operator in PHP 8
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
- Related Articles
- PHP Execution Operator
- PHP Operator Precedence
- Double not (!!) operator in PHP
- PHP Scope Resolution Operator (::)
- PHP Error Control Operator
- Difference between !== and ==! operator in PHP
- Difference between the Ternary operator and Null coalescing operator in php
- Attributes in PHP 8
- Comparison between "&&" and "AND" operator in PHP.
- Difference between the and$ operator in php
- Number comparisons in PHP 8
- Named Arguments in PHP 8
- Union Type in PHP 8
- Match Expression in PHP 8
- fdiv() function in PHP 8

Advertisements