Sobes.tech
Junior — Middle

How is the guaranteed creation of only one instance of the Singleton class implemented?

sobes.tech AI

Answer from AI

To ensure only one instance of the Singleton class is created in PHP, the following are usually used:

  • A private constructor to prevent instantiation from outside.
  • A static private property that holds the single instance.
  • A public static method (e.g., getInstance()) that returns this instance, creating it on the first call.

Example implementation of Singleton in PHP:

class Singleton {
    private static $instance = null;

    private function __construct() {
        // private constructor
    }

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

    private function __clone() {
        // prevent cloning
    }

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

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

This approach guarantees that only one instance of the Singleton class exists in the application.