Singleton mode : Makes an object of a class the only instance in the system.
The most common use of a single case pattern in PHP is database operations. To avoid having multiple connections to the database in the system, wasting system resources, you can use the single example mode. Use an instance of each database operation.
Simple example
Class AClass {
To store your own instance
public static $instance;
Privatisation constructor to prevent external instantiation of objects
Private Function __construct () {}
Privatization cloning function to prevent external cloning of objects
Private Function __clone () {}
static method, single instance access to the unified portal
public static function getinstance () {
if (!) ( Self:: $instance instanceof Self)) {
Self:: $instance = new self ();
}
Return self:: $instance;
}
Test
Public Function test () {
Return to "done";
}
Privatization cloning function to prevent external cloning of objects
Private Function __clone () {}
}
Class Bclass extends aclass{
}
Get instance
$aclass = Aclass::getinstance ();
$bclass = Bclass::getinstance ();
Call method
echo $aclass->test ();
For some of the larger applications, may be connected to multiple databases, then a different database common object may cause problems, such as the allocation of connection handle, we can by the $instance into an array, through different parameters to control
Simple example
Class DB {
To store your own instance
public static $instance = Array ();
public $conn;
Privatisation constructor to prevent external instantiation of objects
Private Function __construct ($host, $username, $password, $dbname, $port) {
$this->conn = new Mysqli ($host, $username, $password, $dbname, $port);
}
static method, single instance access to the unified portal
public static function getinstance ($host, $username, $password, $dbname, $port) {
$key = $host. ":" $port;
if (!) ( Self:: $instance [$key] instanceof self)) {
Self:: $instance [$key] = new self ($host, $username, $password, $dbname, $port); #实例化
}
Return self:: $instance [$key];
}
Query
Public Function Query ($QL) {
return $this->conn->query ($sql);
}
Privatization cloning function to prevent external cloning of objects
Private Function __clone () {}
Releasing resources
Public Function __destruct () {
$this->conn->close ();
}
}