Home >Backend Development >PHP Tutorial >How Can PHP 8's Null Safe and Null Coalescing Operators Simplify Object Property Access?
Leveraging Null Safe Operator and Null Coalescing Operator in PHP 8
In PHP coding, you may encounter situations where you wish to access properties or methods of an object only if the object is not null. Traditionally, this required verbose conditional statements.
Safe Navigation in PHP 8
PHP 8 introduces the null safe operator (?->), which allows you to safely navigate objects without causing fatal errors due to null values. In conjunction with the null coalescing operator (??), you can elegantly chain operator calls.
Example
Consider the following code:
echo $data->getMyObject() != null ? $data->getMyObject()->getName() : '';
With the null safe operator, you can simplify this to:
echo $data->getMyObject()?->getName() ?? '';
In this case, if $data is null, the chain is terminated, and the result will be null.
Operators in the Chain
The operators that inspect an object's properties or methods are part of the null-safe chaining:
Example:
$string = $data?->getObject()->getName() . " after";
If $data is null, $string becomes null. " after" since concatenation is not part of the chain.
The above is the detailed content of How Can PHP 8's Null Safe and Null Coalescing Operators Simplify Object Property Access?. For more information, please follow other related articles on the PHP Chinese website!