This content originally appeared on DEV Community and was authored by Lakhveer Bawa
PHP is known to have a very bad reputation among developers because of its loose type system and little 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.
References:
This content originally appeared on DEV Community and was authored by Lakhveer Bawa
Lakhveer Bawa | Sciencx (2021-05-26T02:40:44+00:00) What is Null Safety Operator in PHP 8 and why is it next big thing in PHP. Retrieved from https://www.scien.cx/2021/05/26/what-is-null-safety-operator-in-php-8-and-why-is-it-next-big-thing-in-php/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.