The Singleton pattern
Learn the Singleton pattern that ensures a single instance of a class.
What does Singleton do?
The Singleton pattern ensures that a class has only one instance. This instance is typically used for shared resources like a database connection, a configuration manager or a logger.
The core idea is two steps: the constructor is hidden (no new from outside) and a static method returns the single instance. The method creates the instance on the first call and returns the same one on later calls.
Hidden constructor and static getInstance
To implement Singleton, first hide the constructor: private function __construct() {}. This blocks new Singleton() from outside, so the instance count stays under control.
Then write a static getInstance method. It checks a private static field; if the field is null, it creates a new instance and stores it, otherwise it returns the existing one. Every call returns the same instance.
Exercise Write the Singleton class and show the same instance
Write a Singleton class. Make the constructor private; a static getInstance method returns the single instance. Call Singleton::getInstance() twice and print whether they are the same instance with echo $a === $b ? 'same' : 'different';.
Show example solution
Singleton { return self::$instance ??= new Singleton(); }. Then $a = Singleton::getInstance(); $b = Singleton::getInstance(); echo $a === $b ? 'same' : 'different';
Example solution:
<?php
class Singleton {
private static ?Singleton $instance = null;
private function __construct() {}
public static function getInstance(): Singleton {
return self::$instance ??= new Singleton();
}
}
$a = Singleton::getInstance();
$b = Singleton::getInstance();
echo $a === $b ? 'same' : 'different';
Test yourself
-
What does the Singleton pattern guarantee?
- That the class runs faster
- That there is a single instance (e.g. a database connection)
- That all methods are hidden
- That new fields are added to the class
Show answer
That there is a single instance (e.g. a database connection) — Correct. Singleton guarantees that a class has only one instance.
-
The method that returns the single instance
<?php class Singleton { private static ?Singleton $instance = null; private function __construct() {} public static ____(): Singleton { return self::$instance ??= new Singleton(); } public function tag(): string { return 'S'; } } $s = Singleton::getInstance(); echo $s->tag();Show answer
<?php class Singleton { private static ?Singleton $instance = null; private function __construct() {} public static getInstance(): Singleton { return self::$instance ??= new Singleton(); } public function tag(): string { return 'S'; } } $s = Singleton::getInstance(); echo $s->tag(); -
Match the Singleton concepts
- __construct
- hidden constructor
- getInstance
- returns the single instance
- self::$instance
- stores the instance
- private
- blocks outside new