
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements