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.

Example

<?php
   class database {
      public static $connection;
      private function __construct(){
         echo "connection created";
      }
      public function connect(){
         if(!isset(self::$connection)){
            self::$connection = new database();
         }
         return self::$connection;
      }
   }
   $db = database::connect();
   $db2 = database::connect();
?>

Output

connection created

Explanation

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.

raja
Published on 27-Jun-2019 18:11:29
Advertisements