Refactoring to null safe operator In this refactoring we make use of the nullsafe operator, so we can get null back without blowing our code https://wiki.php.net/rfc/nullsafe_operator
requires: php 8.0.0

As of PHP 8.0.0, you can make use of the null safe operator. It is fairly common to only want to call a method or fetch a property on the result of an expression if it is not null. Currently in PHP < 8.0.0 , checking for null leads to deeper nesting and repetition, this can be avoided now.

Original code



        

        private function getSession()
        {
            return (object)['user' => new class {
                public function getAddress()
                {
                return (object)['country' => "Belgium"];
                }
            }];
        }
       

        $session $this->getSession();
        
$country null;

        if (
$session !== null) {
            
$user $session->user;

            if (
$user !== null) {
                
$address $user->getAddress();

                if (
$address !== null) {
                    
$country $address->country;
                }
            }
        }

        

Refactored code



        

        private function getSession()
        {
            return (object)['user' => new class {
                public function getAddress()
                {
                    return (object)['country' => "Belgium"];
                }
            }];
        }
       

        $session $this->getSession();
        
$country $session?->user?->getAddress()?->country;

        
// setting the session var to null will not blow up our code
        
$session null;
        
$country2 $session?->user?->getAddress()?->country;


        

Here is the output of the code

This is the output of original

Belgium

This is the output of refactor

Belgium

This is the output of refactor example 2

Want to learn more from LLoadout ?

LLoadout is your loadout for Laravel, helping you kickstart your development process. Besides this refactoring site we also make some cool packages and video tutorials !

Go to LLoadout on github