Home >Backend Development >PHP Tutorial >In PHP, what is the concept of singleton design pattern?

In PHP, what is the concept of singleton design pattern?

WBOY
WBOYforward
2023-08-18 14:25:071209browse

Singleton pattern ensures that a class has only one instance and provides a global access point. It ensures that only one object is available and under control in the application. The Singleton pattern provides a way to access its unique object directly without instantiating 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, we follow the singleton pattern, so the object $db2 cannot be created. Only one object is created and is available throughout the application.

The above is the detailed content of In PHP, what is the concept of singleton design pattern?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete