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.
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;
}
}
}
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;
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