As an object creation mode, the singleton mode ensures that a certain class has only one instance, instantiates itself and provides this instance globally to the entire system. It does not create a copy of the instance, but returns a reference to the instance stored internally in the singleton class.
(1). A static member variable that holds the only instance of the class is required: private static $_instance;
(2). Constructors and clone functions must be declared private to prevent external programs from creating new classes and thereby losing the meaning of the singleton mode:
private function __construct() { $this->_db = pg_connect('xxxx'); } private function __clone() { }
(3). A public static method (usually the getInstance method) must be provided to access this instance, thereby returning a reference to the unique instance:
public static function getInstance() { if(! (self::$_instance instanceof self) ) { self::$_instance = new self(); } return self::$_instance; }
Why use PHP singleton pattern?
1. PHP is mainly used in database applications, so there will be a large number of database operations in an application. Using the singleton mode can avoid a large number of resources consumed by new operations.
2. If a class is needed to globally control certain configuration information in the system, it can be easily implemented using the singleton mode.