January 23, 2023 | Posted in PHP
The nullsafe operator (also known as the “null coalescing operator”) is a new operator introduced in PHP 8.0, which allows you to safely access nested properties or methods of an object without having to check for null values at each level.
The nullsafe operator is represented by two question marks “??” and is used to check whether a variable is null or not; if it’s null, it returns the right value.
For example, if you have an object $user
and you want to access the email
property, you would normally have to check if the object is null before accessing the property:
$email = ($user !== null) ? $user->email : null;
With the nullsafe operator, you can do this in a more concise way:
$email = $user?->email;
You can chain the nullsafe operator to access nested properties or methods. For example:
$address = $user?->getAddress()?->getStreet();
This will return the street
property of the Address
object, if $user
and getAddress()
the method returns non-null values. If either $user
or the getAddress()
method return null, it will return null.
The nullsafe operator helps to reduce the number of null checks and make the code more readable; it’s a good practice to use it when you have nested properties or methods.