Sobes.tech
Junior — Middle

Can you explain how the Singleton pattern is implemented and how it ensures a single instance of a class?

sobes.tech AI

Answer from AI

The Singleton pattern guarantees that a class has only one instance and provides a global point of access to that instance.

How Singleton is implemented in PHP:

  • A private static property is created to hold the class instance.
  • The constructor is made private or protected to prevent creating objects from outside.
  • A public static method (usually getInstance()) is created, which checks if an instance already exists, and if not — creates it, then returns it.

Example:

class Singleton {
    private static $instance = null;

    private function __construct() {
        // private constructor
    }

    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    // prevent cloning
    private function __clone() {}

    // prevent unserialization
    private function __wakeup() {}
}

// Usage
$singleton = Singleton::getInstance();

Thus, the class controls the creation of its single instance and does not allow creating new objects directly.