Some code interpretation in PHP

class U_Pizza_Install
{

    protected static $instance = null;

    public static function instance()
    {
        if (is_null(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }


    public function __construct()
    {
        $this->include();
    }
    public function include()
    {
        require_once U_PIZZA_PATH . 'includes/pizza-functions.php';
        require_once U_PIZZA_PATH . 'includes/pizza.php';

        U_Pizza::instance();
    }
}

function init_plugin_pizza()
{
    U_Pizza_Install::instance();
}

What is this part doing → U_Pizza_Install::instance();

Is the class calling the function “instance”?

The class constructor is calling the static method instance(); instance is a static function that checks to see if there exists an object of its type; if so, it self-references. If not, it creates a new instance of itself and returns it.

1 Like

Thanks, Are there any examples to better understand it?

I mean… it’s probably the most stripped-down version you’re going to find out there…

It’s a lesson on the difference between instance methods and static methods.

1 Like

It’s known as the Singleton Pattern that ensures there will only be ever one instance of the U_Pizza_Install class, not multiple.

It used to be quite popular but its now considered an anti-pattern, as Dependency Injection should be used instead.

In this specific case the class only includes some files, which shouldn’t be done in a class at all, but either in a function or (preferred) through composer.

1 Like

What will be the benefit?

Because then you have a single source of what files need to be loaded, instead of spreading it all over the place at runtime.