Press "Enter" to skip to content

Singleton (PHP)

Singleton is a creational design pattern, which ensures that only that object exists in the memory and provides a single point of access to it for any other code.


namespace JSTechRoad\Singleton;

// The Singleton class defines the `GetInstance` method 
// that serves as an alternative to constructor and lets 
// clients access the same instance of this class forever.
class Singleton
    // The Singleton's instance is stored in a static field
    private static $instances = [];

    // The Singleton's constructor should always be private
    // to prevent direct construction calls with the `new` operator.
    protected function __construct() { }

    // Singletons should not be cloneable.
    protected function __clone() { }

    // Singletons should not be restorable from strings.
    public function __wakeup()
        throw new \Exception("Cannot unserialize a singleton.");

    // static method that controls the access to the singleton
    // instance. 
    public static function getInstance(): Singleton
        $cls = static::class;
        if (!isset(self::$instances[$cls])) {
            self::$instances[$cls] = new static();

        return self::$instances[$cls];

    // any singleton should define some business logic, which can be
    // executed on its instance.
    public function someFunction()
        // ...

// testing function
function clientCode()
    $s1 = Singleton::getInstance();
    $s2 = Singleton::getInstance();
    if ($s1 === $s2) {
        echo "Singleton works!";
    } else {
        echo "Singleton failed!";