Null Safe Operator for PHP 7.x or Earlier

Viewed 11

PHP 8 has introduced an amazing code fallback tool, Null Safe Operator, eg:

$country = $session?->user?->getAddress()?->country;

It prevents you create a lot of comparisons of all whole object tree, Null Coalesce Operator not plays well here (PHP 7.x or Earlier) beacuse above code has an method which will throw an exception because their main class is null. Here, Null Safe Operator prevents an exception.

Well, there are some hack method to emulate this behaviour into earlier versions of PHP (<= 7.X)?

Fallback to some generic class with magic methods where ever returns null can be handful.

0 Answers
Related