New PHP 8 features - Nullsafe operator

New PHP 8 features - Nullsafe operator

PHP 8 is just around the corner (November 26, 2020 to be precise) and as always this comes with breaking changes but with it comes many new features and optimisations.

Most companies will still use PHP 7 for now but it is certainly a good time to play around with PHP 8 and see what new magic this brings - this blog post won't explain how to install PHP 8 (i'll do this in a future post perhaps).

Nullsafe operator

One of the coolest features of PHP 8 is the Nullsafe operator - personally I don't understand why this wasn't shipped with PHP years ago but what does this actually do?

<?php
class User {
    public function profile()
    {
        return new Profile; // this would be a SQL query 
    }
}

class Profile {
    public function employment()
    {
        return 'Basketball player'; // this would be a SQL query etc..
    }
}

Imagine the following code above - pretty standard stuff, we have 2 classes - one for the user, and another for their profile. The data is hard-coded for the example but in real-life this would be likely coming from some form of a SQL database.

To grab the the employment data we would run code like the following :-

$user = new User;
$profile = $user->profile();
echo $profile->employment();

This all great, but what if the user doesn't a profile and it has returned null from the database.

class User {
    public function profile()
    {
        return null; // let's pretend the db returned null (no profile exists)
}

In this case on PHP 7 we would get a fatal error as it cannot reach the employment() and we'd see the dreaded Call to a member function employment on null error. We would have to use a condition to only call the employment function when a profile exists as follows.

$user = new User;
$profile = $user->profile();
if ($profile) {
    echo $profile->employment();
}

This works - but having lots of conditional statements like this throughout your codebase takes up additional space and can become a little messy, however we can minimise this by using the nullsafe operator in PHP 8 using an extremely simple manner.

$user = new User;
echo $user->profile()?->employment();

Now those 3 lines have just become 1!

Using the question mark (the nullsafe operator) after profile() we simply are saying if this doesn't exist then simply return null (and don't blow up as it does in PHP 7) - if the profile does exist however we will return the data from the employment function (in our base it would display "Basketball player".

Very simple and very effective - I can see this becoming one of PHP 8's most widely used new features because it is so easy to use and it makes such a different in the amount of code you write = especially if you have lots of these conditionals running throughout your code.