Nhan Nguyen Nhan Nguyen - 5 months ago 10
PHP Question

Singleton design pattern in PHP

I have a question about singleton design pattern.
When we apply singleton for our class, we need to set class' constructor private so we can not instantiate the class normally, but we also instantiate it in class context (if the object we need doesnt exist). The question is why dont private constructor prevent us from instantiate class in class context?

Answer

Visibility modifiers are for specifying who can be trusted to interact with this method or property. The idea being that each method and property has a specific purpose and should be used in specific ways; e.g. certain methods should only be called at certain times and certain properties should only ever be set to certain values. If each method and property is public, any code can interact with it at any time, even if it's not "qualified" to do so correctly. To minimise problems resulting from that, visibility can be restricted to a family of classes only (protected) or one specific class alone (private).

There is no difference whether this interaction is in a static or object context, or even whether it's the "current" object or another instance of it. The class is expected to "be qualified" to interact with the method correctly, so it is allowed to do so. This might surprise you, but even this works just fine according to this philosophy:

class Foo {
    private $bar;

    public static baz() {
        $obj = new Foo;
        $obj->bar = 42;
    }
}

The class is not manipulating $this, it's manipulating a private property of an instance of itself, and that's allowed. So is calling its own constructor.

Comments