PHP constructors without parameters or executable code

Viewed 904

While learning about design patterns I have come across the singleton pattern:

class Singleton
{
    private static $instance = null;

    private function __construct()
    {
    }

    public static function getInstance()
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }

        return self::$instance;
    }
}

I'm having a hard time understanding what the constructor does in this circumstance. There isn't any code being executed between the braces? How does this work? Thanks.

2 Answers

The constructor marked private is used to avoid the instantiation of the singleton class, so there is always only a single one.

For example we cannot do this:

$singleton = new Singleton();

It yields:

Fatal error: Call to private Singleton::__construct() from invalid context

You must fetch the singleton:

$singleton = Singleton::getInstance();

As the constructor is marked as private, it can only be called from within the class. This allows the method getInstance to create a new instance-

self::$instance = new self();

But (as pointed out) if you tried to create an instance of this class in your own code - it will give an error as you can't call the private constructor.

This allows a class to restrict how instances of this object are created and therefore in this case limit it to 1 copy.

Related