PHP Single-instance mode details, PHP mode detailed introduction
The concept of a singleton pattern
A singleton pattern is a design pattern in which a class has only one instance of an object in the entire application. Specifically, as an object is created, a singleton pattern ensures that a class has only one instance, and instantiates itself and provides this instance to the whole system globally. Instead of creating an instance copy, it returns a reference to the instance stored inside the singleton class.
Characteristics of the Singleton model
The main feature of the singleton mode is " three private One ":
Requires a private static member variable that holds a unique instance of the class
Constructors must be declared private to prevent external programs from being new to one object thereby losing the meaning of a singleton
The clone function must be declared private to prevent the object from being cloned
You must provide a public static method that accesses this instance (typically named getinstance), which returns a reference to the unique instance.
Reasons and scenarios for using singleton mode
In most of the PHP application there will be a large number of database operations, if not a singleton mode, that every time to new operations, but each time new will consume a lot of system resources and memory resources, and each open and close the database is a great test and waste of the database. Therefore, singleton patterns are often used in database operation classes.
Similarly, if a class is needed in the system to control some configuration information globally, it can be easily implemented using singleton mode.
PHP Single-instance mode implementation
The following is a PHP singleton schema implementation of database operation class framework
<?php class db{const db_host= ' localhost '; const db_name= '; const db_user= '; const db_pwd= "; private $_db;//Save Instance Private Static variable private static $_instance; Constructors and clone functions are declared private function __construct () { //$this->_db=mysql_connect ();} Private Function __clone () { //implementation}//access to the public static method of the instance getinstance () { if (! Self::$_instance instanceof Self) { self::$_instance=new self (); } or if (self::$_instance===null) { self::$_instance=new Db (); } return self::$_instance; } public Function Fetchall () { //implementation} Public function Fetchrow () { //implementation}}//class external Get instance Reference $db =db::getinstance (); >
http://www.bkjia.com/PHPjc/1024910.html www.bkjia.com true http://www.bkjia.com/PHPjc/1024910.html techarticle PHP Singleton mode in detail, PHP mode detailed introduction to the concept of Singleton mode singleton mode refers to the entire application of a class only one object instance design pattern. In particular, as to ...