Home  >  Article  >  Backend Development  >  Detailed explanation and sample code of php singleton mode

Detailed explanation and sample code of php singleton mode

怪我咯
怪我咯Original
2017-07-12 14:01:361369browse

This article introduces PHPsingle case mode. The article explains the concept of singleton mode, the characteristics of singleton mode, the reasons and scenarios for using singleton mode, and PHP singleton mode code examples, and the required code Farmers can refer to the following

Detailed explanation of PHP singleton mode


##Singleton Pattern singleton mode or single element mode)

The singleton pattern ensures that a class has only one instance, instantiates itself and provides this instance to the entire system.

The singleton mode is a common

design pattern. In computer systems, thread pools, caches, log objects, dialog boxes, printers, database operations, Graphics card drivers are often designed as singletons.

There are three types of singleton modes: lazy-style singleton, hungry-style singleton, and registration-style singleton.

The singleton mode has the following three characteristics:

1. There can only be one instance.

2. You must create this instance yourself.

3. This instance must be provided to other objects.

So why use PHP singleton mode?

One of the main application scenarios of PHP is the scenario where the application deals with the database. In an application, there will be a large number of database operations. For the behavior of database handle

connecting to the database, the singleton mode can be used. Avoid a large number of new operations. Because every new operation consumes system and memory resources.

PHP singleton mode implementation

The following is a framework for PHP singleton mode to implement database operation classes

<?php
 class Db{
 const DB_HOST=&#39;localhost&#39;;
 const DB_NAME=&#39;&#39;;
 const DB_USER=&#39;&#39;;
 const DB_PWD=&#39;&#39;;
 private $_db;
 //保存实例的私有静态变量
 private static $_instance;
 //构造函数和克隆函数都声明为私有的
 private function construct(){
 //$this->_db=mysql_connect();
 }
 private function clone(){
 //实现
 }
 //访问实例的公共静态方法
 public static function getInstance(){
 if(!(self::$_instance instanceof self)){
 self::$_instance=new self();
 }
 //或者
 if(self::$_instance===null){
 self::$_instance=new Db();
 }
 return self::$_instance;
 }
 public function fetchAll(){
 //实现
 }
 public function fetchRow(){
 //实现
 }
 }
 //类外部获取实例的引用
 $db=Db::getInstance();
?>

The above is the detailed content of Detailed explanation and sample code of php singleton mode. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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