Sobes.tech
Junior

What is the purpose of the Singleton pattern?

sobes.tech AI

Answer from AI

The Singleton is used to guarantee that a class has only one instance and to provide a global point of access to it. It is applied where control over object creation is necessary, for example:

  • Working with a database (single connection).
  • Managing application configuration.
  • Logging (single logger instance).

Example implementation:

<?php

class Singleton {
    private static ?self $instance = null;

    private function __construct() {
        // Private constructor prevents creating new instances from outside
    }

    private function __clone() {
        // Prohibit cloning of the instance
    }

    private function __wakeup() {
        // Prohibit unserializing of the instance
    }

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

    public function someMethod() {
        // Logic of the instance
        return "Hello from Singleton!";
    }
}

// Getting the instance
$singleton1 = Singleton::getInstance();
$singleton2 = Singleton::getInstance();

// $singleton1 and $singleton2 point to the same object
// var_dump($singleton1 === $singleton2); // true echo $singleton1->someMethod(); // Hello from Singleton!
What is the purpose of the Singleton pattern? — PHP - sobes.tech