CreationalPHPverifiedVerified

Singleton Pattern in PHP

Ensures a class has only one instance and provides a global point of access to it.

How to Implement the Singleton Pattern in PHP

1Step 1: Define the Singleton class with a private constructor

class Singleton
{
    private static ?self $instance = null;

    private function __construct() {}

    // Prevent cloning and unserialization
    private function __clone() {}
    public function __wakeup(): never
    {
        throw new \RuntimeException('Cannot unserialize singleton');
    }

2Step 2: Implement the static getInstance method

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

    // Business methods
    public function doSomething(): void
    {
        echo "Singleton method called\n";
    }
}

3Step 3: Verify only one instance exists

$a = Singleton::getInstance();
$b = Singleton::getInstance();
var_dump($a === $b); // true

Singleton Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Singleton Pattern in the Real World

Think of a country’s president. There can only be one at any time. When anyone needs to communicate with the president, they don’t create a new one—they access the existing one through the official channel (the static method).