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
Release: 2023-08-18 14:28:02
forward
1192 people have browsed it

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();
?>
Copy after login

Output

connection created
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template