Reading Time: < 1 minute

The null object pattern aims to replace null with actual objects, objects that behave differently because they represent the “absence” of the real object. Another benefit of using this pattern is that classes become more representative of the real world. You wouldn’t need to worry about null anymore.

From Front Line PHP Book

Why Is The Null Object Pattern Beneficial?

Null Object Pattern simplifies code by avoiding if else conditions to check if the object is null or not. For example, if (!is_null($obj)) { $obj->callSomeFunction(); } will be $obj->callSomeFunction();

Code Examples

Imagine, we have two types of users called premium and standard users. Both type of users have subscribed to your blogging site. Premium users have access to watch the video stats but standard users don’t have the access.

Note: We can achieve the above need in several ways.

<?php

class VideoController
{
   
    // Dependency Injection Of UserInterface
    public function __construct(private UserInterface $user)
    {
    }

    /**
     * Show video stats
     */
    public function showStats()
    {
        // Let's assume this videoStats is only available when the user is premium
        // not for the standard user
        $this->user->videoStats();
    }
}

Note: If you will notice, in the above code snippet, we did not check if the videoStats() is set eg. is_null() or isset() instead just used it

<?php

interface UserInterface
{
    public function videoStats();
}
<?php

class PremiumUser implements UserInterface
{
    public function videoStats()
    {
        print '70% video watched!'; // Hard coded for demo purpose
    }
}
<?php

class NullUser implements UserInterface
{
    public function videoStats()
    {
        // do nothing
        return '';
    }
}
<?php

//VideoController 

$premiumUser = new VideoController(new PremiumUser());
$premiumUser->showStats();

$standardUser = new VideoController(new NullUser());
$standardUser->showStats();

Reference

https://designpatternsphp.readthedocs.io/en/latest/Behavioral/NullObject/README.html

Check how Symfony console uses Null Object Pattern: https://github.com/symfony/console/blob/5.4/Output/NullOutput.php

Front Line Php Book