The Singleton pattern makes sure only one object of a class exists. It helps when you want to share the same data or settings everywhere in your program.
When you want to control access to a shared resource like a database connection.
When you need to keep global settings consistent across your app.
When creating a logger that writes messages to one file.
When you want to avoid creating many copies of a heavy object.
When you want to coordinate actions from different parts of your program.
Syntax
PHP
<?php
class Singleton {
privatestatic ?Singleton $instance = null;
privatefunction __construct() {
// Private constructor stops direct creation
}
publicstaticfunction getInstance(): Singleton {
if (self::$instance === null) {
self::$instance = new Singleton();
}
return self::$instance;
}
publicfunction sayHello(): void {
echo"Hello from Singleton!\n";
}
}
?>
The constructor is private to stop creating new objects from outside.
The static method getInstance() returns the same object every time.
Examples
This gets the single object and calls a method on it.
PHP
<?php
// Get the single instance
$one = Singleton::getInstance();
$one->sayHello();
You cannot create a new object directly because the constructor is private.
PHP
<?php
// Trying to create directly will cause error// $two = new Singleton(); // Not allowed// Correct way:
$two = Singleton::getInstance();
This shows that both variables hold the same instance.
PHP
<?php
// Both variables point to the same object
$a = Singleton::getInstance();
$b = Singleton::getInstance();
var_dump($a === $b); // true
Sample Program
This program shows how to get the single instance of the class and confirms both variables point to the same object.
PHP
<?php
class Singleton {
privatestatic ?Singleton $instance = null;
privatefunction __construct() {
// Private constructor
}
publicstaticfunction getInstance(): Singleton {
if (self::$instance === null) {
self::$instance = new Singleton();
}
return self::$instance;
}
publicfunction greet(): void {
echo"Hello from the Singleton!\n";
}
}
// Get the instance and call greet
$instance1 = Singleton::getInstance();
$instance1->greet();
// Get the instance again
$instance2 = Singleton::getInstance();
// Check if both are the sameif ($instance1 === $instance2) {
echo"Both variables hold the same instance.\n";
} else {
echo"Different instances exist.\n";
}
OutputSuccess
Important Notes
Singletons can make testing harder because they keep state globally.
Use Singleton only when you really need one shared object.
Remember to keep the constructor private to prevent new objects.
Summary
Singleton pattern ensures only one object of a class exists.
Use getInstance() to get the single object.
It helps share data or resources safely across your program.
Practice
(1/5)
1. What is the main purpose of the Singleton pattern in PHP?
easy
A. To ensure only one instance of a class is created
B. To allow multiple instances of a class
C. To inherit properties from multiple classes
D. To create objects without a constructor
Solution
Step 1: Understand Singleton pattern goal
The Singleton pattern is designed to restrict a class to a single instance.
Step 2: Compare options with Singleton purpose
Only To ensure only one instance of a class is created correctly states this purpose; others describe different concepts.
Final Answer:
To ensure only one instance of a class is created -> Option A
Quick Check:
Singleton = single instance only [OK]
Hint: Singleton means one and only one instance [OK]
Common Mistakes:
Thinking Singleton allows multiple instances
Confusing Singleton with inheritance
Believing Singleton removes constructors
2. Which of the following is the correct way to declare the static instance variable in a Singleton class in PHP?
easy
A. public static $instance;
B. private static $instance;
C. protected $instance;
D. static $instance;
Solution
Step 1: Identify visibility for Singleton instance
The instance variable must be private static to restrict access and keep one shared instance.
Step 2: Check options for correct syntax and visibility
private static $instance; uses private static, which is correct. Others either lack visibility or static keyword.
Final Answer:
private static $instance; -> Option B
Quick Check:
Singleton instance is private static [OK]
Hint: Singleton instance must be private and static [OK]
Common Mistakes:
Using public instead of private
Omitting static keyword
Using protected instead of private
3. What will be the output of the following PHP code?
class Singleton {
private static ?Singleton $instance = null;
public int $value;
private function __construct() { $this->value = 10; }
public static function getInstance(): Singleton {
if (self::$instance === null) {
self::$instance = new Singleton();
}
return self::$instance;
}
}
$obj1 = Singleton::getInstance();
$obj2 = Singleton::getInstance();
$obj2->value = 20;
echo $obj1->value;
medium
A. 10
B. null
C. 20
D. Error
Solution
Step 1: Understand Singleton instance sharing
Both $obj1 and $obj2 refer to the same Singleton instance.
Step 2: Trace value changes
Changing $obj2->value to 20 affects $obj1->value because they are the same object.
Final Answer:
20 -> Option C
Quick Check:
Singleton shares one object, so value = 20 [OK]
Hint: Singleton returns same object, changes reflect everywhere [OK]
Common Mistakes:
Assuming separate objects for each getInstance call
Expecting original value 10 after change
Thinking code causes error
4. Identify the error in this Singleton implementation:
class Singleton {
private static $instance;
private function __construct() {}
public static function getInstance() {
if (!isset(self::$instance)) {
return new Singleton();
}
return self::$instance;
}
}
medium
A. No error, code is correct
B. Constructor should be public
C. Static variable should be public
D. getInstance() does not assign the new object to static instance
Solution
Step 1: Check getInstance method logic
The method creates a new Singleton but does not save it to self::$instance.
Step 2: Identify missing assignment
Without assigning, every call returns a new object, breaking Singleton pattern.
Final Answer:
getInstance() does not assign the new object to static instance -> Option D
Quick Check:
Missing assignment breaks Singleton [OK]
Hint: Always assign new instance to static variable in getInstance [OK]
Common Mistakes:
Making constructor public
Not assigning instance in getInstance
Changing static variable visibility incorrectly
5. You want to extend a Singleton class in PHP but ensure the child class also follows Singleton rules independently. Which approach is best?
hard
A. Use separate static instance variables in parent and child classes
B. Share the parent's static instance variable in the child class