Php design pattern Singleton pattern (single element pattern)
Singleton mode:
As the object creation mode, the singleton mode ensures that a class has only one instance, and the instance is self-instantiated and global to the entire system. It does not create instance copies, but returns a reference to the instance stored in the singleton class.
(1). You need a static member variable that saves the unique instance of the class: private static $ _ instance;
(2) constructor and clone functions must be declared private to prevent external programs from losing the meaning of Singleton mode due to new classes:
Private function _ construct () {$ this-> _ db = pg_connect ('xxx');} private function _ clone (){}
(3) You must provide a public static method (usually the getInstance method) to access the instance and return a reference of a unique instance:
Public static function getInstance () {if (! (Self: $ _ instance instanceof self) {self: $ _ instance = new self ();} return self ::$ _ instance ;}
Why use the PHP Singleton mode?
1. php applications mainly lie in database applications. Therefore, a large number of database operations exist in an application. Using the singleton mode can avoid the resources consumed by a large number of new operations.
2. If you need a class in the system to globally control some configuration information, you can use the singleton mode to conveniently implement it.