What is singleton design concept in PHP?

Object Oriented ProgrammingPHPProgramming

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.


   class database {
      public static $connection;
      private function __construct(){
         echo "connection created";
      public function connect(){
            self::$connection = new database();
         return self::$connection;
   $db = database::connect();
   $db2 = database::connect();


connection created


In the above example as we are following a singleton pattern so the object $db2 can't be created. Only a single object will be created and i.e available all across the application.

Updated on 29-Jun-2020 11:38:58