PHP is known to have a very bad reputation among developers because of its loose type system and weak technical design.
However with every new version, PHP is changing the perception of developers.
Recent improvements in PHP 7 and then PHP 8 brought many features that you would only see in languages like Java, C++, Dart etc.
One of those features/improvement brought by PHP 8 is easier Null Safety.
Null Safety has lot of significance in programming, as Program Crashes caused by Null Values are highly popular.
What is Null Safety Operator:
Null-safe operator is a new syntax in PHP 8.0, that provides optional chaining feature to PHP.
The null-safe operator allows reading the value of property and method return value chaining, where the null-safe operator short-circuits the retrieval if the value is null, without causing any errors.
The syntax is similar to the property/method access operator (->), and following the nullable type pattern, the null-safe operator is ?->.
$foo?->bar?->baz;
Null safe operator silently returns null if the expression to the left side evaluates to null.
class Customer {
public function getAddress(): ?Address {}
}
class Address {
public function getCountry(): string {}
}
$country = $customer->getAddress()->getCountry();
In the snippet above, the Customer::getAddress() method return value is nullable; It can return a null value, or an object of Address class.
The $customer->getAddress()->getCountry() chain is not "null safe", because the return value of getAddress can be null, and PHP throws an error when it tries to call getCountry() method:
Fatal error: Uncaught Error: Call to a member function getCountry() on null in ...:...
To safely access the address, it was necessary to check the null return values before further accessing the return value.
$address = $customer->getAddress();
$country = $address ? $address->getCountry() : null;
$address = $customer->getAddress();
if ($address) {
$country = $address->getCountry();
}
else {
$country = null;
}
The null-safe operator solves this by short-circuiting the property/method access, and returning null immediately if the left side of the operator is null, without executing the rest of the expression.
Top comments (3)
Question marks.
Question marks everywhere.
yes, thats how it works, I learned about significance of Null Safety from Dart / Flutter, and realized, we should be using it.
The way to "make things work" like that without this operator was to use the nul-object pattern