What is singleton design concept in PHP?

Singleton Pattern ensures that a class has only one instance and provides a global point to access it. It ensures that only one object is available all across the application in a controlled state. Singleton pattern provides a way to access its only object which can be accessed directly without the need to instantiate the object of the class.

Example

<?php
    class database {
        public static $connection;
        
        private function __construct(){
            echo "connection created<br>";
        }
        
        public static function connect(){
            if(!isset(self::$connection)){
                self::$connection = new database();
            }
            return self::$connection;
        }
    }
    
    $db = database::connect();
    $db2 = database::connect();
    
    // Both variables point to the same instance
    var_dump($db === $db2);
?>

Output

connection created
bool(true)

Key Benefits

The Singleton pattern offers several advantages −

  • Memory efficiency: Only one instance exists throughout the application
  • Global access: The instance can be accessed from anywhere in the code
  • Controlled instantiation: Prevents multiple instances from being created accidentally

Conclusion

The Singleton pattern is useful for classes like database connections, logging, or configuration settings where only one instance should exist. The private constructor prevents direct instantiation, ensuring controlled object creation.

Updated on: 2026-03-15T08:14:29+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements