Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 26, 2021 02:40 am GMT

What is Null Safety Operator in PHP 8 and why is it next big thing in PHP

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:

wondering
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:

PHP 8 new Features.

bye


Original Link: https://dev.to/bawa_geek/what-is-null-safety-operator-in-php-8-and-why-is-it-next-big-thing-in-php-377b

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To