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
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 handleconnecting 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='localhost'; const DB_NAME=''; const DB_USER=''; const DB_PWD=''; 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!