Recall & Review
beginner
What is the Singleton pattern?
The Singleton pattern ensures a class has only one instance and provides a global point of access to it.Click to reveal answer
beginner
How do you prevent creating multiple instances in a Singleton class in PHP?By making the constructor private or protected, so no other code can create new instances directly.
Click to reveal answer
beginner
What is the purpose of the static method in a Singleton class?
It returns the single instance of the class, creating it if it does not exist yet.
Click to reveal answer
beginner
Why is the Singleton pattern useful in real life?
It is useful when you need only one shared resource, like a database connection, to avoid conflicts and save resources.
Click to reveal answer
intermediate
Show a simple PHP Singleton class structure.class Singleton {
private static ?Singleton $instance = null;
private function __construct() {}
public static function getInstance(): Singleton {
return self::$instance ??= new Singleton();
}
}Click to reveal answer
What keyword is used to prevent creating new instances from outside a Singleton class in PHP?
✗ Incorrect
The constructor is made private to prevent creating new instances from outside the class.
Which method typically returns the single instance in a Singleton pattern?
✗ Incorrect
The getInstance() method returns the single instance, creating it if needed.
Why should the Singleton instance be stored in a static property?
✗ Incorrect
A static property keeps the instance shared and persistent across calls.
Which of these is a common use case for Singleton pattern?
✗ Incorrect
Database connections are often managed as singletons to avoid multiple connections.
What happens if the Singleton constructor is public?
✗ Incorrect
If the constructor is public, other code can create multiple instances, breaking the Singleton pattern.
Explain how the Singleton pattern controls instance creation in PHP.
Think about how the class hides its constructor and uses a static method to give access.
You got /4 concepts.
Describe a real-world scenario where using a Singleton pattern is helpful.
Consider something that should only have one version running at a time.
You got /4 concepts.