The concept of a single case pattern
A single example pattern is a design pattern in which a class has only one object instance in the entire application. Specifically, as an object creation, the singleton pattern ensures that a class has only one instance, and instantiates it itself and provides this instance to the entire system globally. Instead of creating an instance copy, it returns a reference to an instance stored within a singleton class.
Characteristics of a single case model
The main feature of the single case model is " three private One ":
A private static member variable is required to hold a unique instance of the class
Constructors must be declared private to prevent an external program from creating an object that loses the meaning of a single instance
The clone function must be declared private to prevent the object from being cloned
A public static method (usually named getinstance) that accesses this instance must be provided to return a reference to a unique instance.
Reasons and scenarios for using a single case pattern
In most PHP applications there will be a large number of database operations, if you do not use the single example mode, that each time the new operation, 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 of the database and waste. Therefore, a single example pattern is often used in database operations classes.
Similarly, if you need a class in your system to control some configuration information globally, then using a single example pattern can be a convenient implementation.
PHP Single Example mode implementation
Here is a PHP single example schema to implement the database Operation class framework
<?php class db{const db_host= ' localhost ';
Const Db_name= ';
Const db_user= ';
Const db_pwd= ';
Private $_db;
To save the private static variable of an instance $_instance;
Both the constructor and the clone function are declared as proprietary private function __construct () {//$this->_db=mysql_connect (); The Private Function __clone () {//implements}//accesses 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;
The Public Function Fetchall () {//implementation} Public function Fetchrow () {//implementation}}//class Gets the reference of the instance $db =db::getinstance (); ?>