0
0
PHPprogramming~5 mins

Singleton pattern in PHP - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Apublic
Bprivate
Cstatic
Dfinal
Which method typically returns the single instance in a Singleton pattern?
AgetInstance()
Bcreate()
CnewInstance()
Dinit()
Why should the Singleton instance be stored in a static property?
ASo it is shared across all calls and not recreated
BTo allow multiple instances
CTo make it private
DTo make the class abstract
Which of these is a common use case for Singleton pattern?
ALoop counter
BTemporary variable
CDatabase connection
DUser input form
What happens if the Singleton constructor is public?
AThe class becomes abstract
BOnly one instance is created
CThe static method fails
DMultiple instances can be created
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.