Pretty soon PHP8 will be mandatory all over the web. Today we’ll look at the Nullsafe operator to reduce a few lines of code.
Instead of null check conditions, you can now use a chain of calls with the new nullsafe operator. When the evaluation of one element in the chain fails, the execution of the entire chain aborts and the entire chain evaluates to null.
//PHP7
$country = null;
if ($session !== NULL){
$user = $session->user;
if($user !== NULL){
$address = $user->getAddress();
}
if($address !== NULL){
$country = $address->country;
}
}
//PHP8
$country = $session?->user?->getAddress()?->country;
Much cleaner don’t you think?
Now get coding!