Bird
Raised Fist0
PHPprogramming~10 mins

Singleton pattern in PHP - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Singleton pattern
Start
↓
Check if instance exists?
Yes→Return existing instance
No↓
Create new instance
↓
Store instance
↓
Return new instance
↓
End
The Singleton pattern checks if an instance exists; if not, it creates one, stores it, and returns it. Otherwise, it returns the stored instance.
Execution Sample
PHP
<?php
class Singleton {
  private static $instance = null;
  private function __construct() {}
  public static function getInstance() {
    if (self::$instance === null) {
      self::$instance = new Singleton();
    }
    return self::$instance;
  }
}
$one = Singleton::getInstance();
$two = Singleton::getInstance();
var_dump($one === $two); // true
?>
This code creates a Singleton class that only allows one instance and returns the same instance every time.
Execution Table
StepActionConditionResultInstance StateOutput
1Call getInstance()self::$instance === nullTruenullCreate new Singleton instance
2Assign new Singleton to self::$instance-Instance storedSingleton object-
3Return self::$instance-Return stored instanceSingleton objectSingleton object
4Call getInstance() againself::$instance === nullFalseSingleton objectReturn existing instance
5Return self::$instance-Return stored instanceSingleton objectSingleton object
6Compare $one === $two-TrueSingleton objectbool(true)
7End--Singleton object-
💡 Execution stops after returning the stored Singleton instance and confirming both variables point to the same object.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 4Final
self::$instancenullSingleton objectSingleton objectSingleton objectSingleton object
$oneundefinedSingleton objectSingleton objectSingleton objectSingleton object
$twoundefinedundefinedundefinedSingleton objectSingleton object
Key Moments - 3 Insights
Why does getInstance() create the object only once?
Because it checks if self::$instance is null (see Step 1 and Step 4 in execution_table). If not null, it returns the existing instance instead of creating a new one.
Why are $one and $two exactly the same object?
Because getInstance() returns the same stored instance each time (see Steps 3 and 5). The comparison in Step 6 confirms they reference the same object.
Why is the constructor private?
To prevent creating new instances outside getInstance(), ensuring only one instance exists (not shown in table but essential for Singleton).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of self::$instance after Step 2?
Anull
Bundefined
CSingleton object
Dbool(true)
💡 Hint
Check the 'Instance State' column at Step 2 in execution_table.
At which step does getInstance() return the existing instance instead of creating a new one?
AStep 1
BStep 4
CStep 3
DStep 6
💡 Hint
Look at the 'Condition' and 'Result' columns for Step 4 in execution_table.
If the constructor was public, what would change in the execution_table?
AMultiple instances could be created outside getInstance()
Bself::$instance would be null after Step 2
CgetInstance() would never create an instance
DThe comparison in Step 6 would be false
💡 Hint
Think about how private constructor controls instance creation (see key_moments).
Concept Snapshot
Singleton pattern ensures a class has only one instance.
Use a private static variable to hold the instance.
Make the constructor private to prevent direct creation.
Provide a public static method to get the instance.
If instance exists, return it; else create and store it.
This pattern controls resource use and consistency.
Full Transcript
The Singleton pattern in PHP uses a private static variable to hold the single instance of a class. The constructor is private to prevent creating new instances directly. The public static method getInstance() checks if the instance exists; if not, it creates and stores it, then returns it. If it exists, it returns the stored instance. This ensures only one object of the class exists. Variables $one and $two both get the same instance, confirmed by comparing them. This pattern is useful when you want to control resource usage or ensure consistent state 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

  1. Step 1: Understand Singleton pattern goal

    The Singleton pattern is designed to restrict a class to a single instance.
  2. 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.
  3. Final Answer:

    To ensure only one instance of a class is created -> Option A
  4. 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

  1. Step 1: Identify visibility for Singleton instance

    The instance variable must be private static to restrict access and keep one shared instance.
  2. 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.
  3. Final Answer:

    private static $instance; -> Option B
  4. 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

  1. Step 1: Understand Singleton instance sharing

    Both $obj1 and $obj2 refer to the same Singleton instance.
  2. Step 2: Trace value changes

    Changing $obj2->value to 20 affects $obj1->value because they are the same object.
  3. Final Answer:

    20 -> Option C
  4. 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

  1. Step 1: Check getInstance method logic

    The method creates a new Singleton but does not save it to self::$instance.
  2. Step 2: Identify missing assignment

    Without assigning, every call returns a new object, breaking Singleton pattern.
  3. Final Answer:

    getInstance() does not assign the new object to static instance -> Option D
  4. 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
C. Make constructor public in child class
D. Avoid inheritance and duplicate Singleton code

Solution

  1. Step 1: Understand Singleton inheritance challenge

    Parent and child classes must maintain separate single instances to avoid conflicts.
  2. Step 2: Use separate static variables

    Each class having its own static instance variable ensures independent Singleton behavior.
  3. Final Answer:

    Use separate static instance variables in parent and child classes -> Option A
  4. Quick Check:

    Separate static instances keep Singleton independent [OK]
Hint: Each class needs its own static instance variable [OK]
Common Mistakes:
  • Sharing static instance causes one instance for both classes
  • Making constructor public breaks Singleton
  • Avoiding inheritance unnecessarily
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard