Home > Article > Backend Development > PHP Design Patterns Singleton Pattern_PHP Tutorial
Singleton mode: Makes an object of a class the only instance in the system.
The most common use of singleton mode in PHP is database operations. To avoid having multiple database connection operations in the system and wasting system resources, you can use the singleton mode. One instance is used for each database operation.
Simple example
class AClass {
// Used to store your own instances
public static $instance;
// Private constructor to prevent external objects from instantiating objects
private function __construct() {}
// Private clone function to prevent external objects from being cloned
private function __clone() {}
// Static method, singleton access unified entrance
public static function getInstance() {
if (!(self::$instance instanceof self)){
Self::$instance = new self();
}
return self::$instance;
}
// test
public function test() {
return "done";
}
// Private clone function to prevent external objects from being cloned
private function __clone() {}
}
class BClass extends AClass{
}
// Get instance
$aclass = AClass::getInstance();
$bclass = BClass::getInstance();
// Call method
echo $aclass->test();
For some relatively large applications, multiple databases may be connected, so different databases sharing a common object may cause problems, such as the allocation of connection handles, etc. We can change $instance into an array and pass different Parameters to control
Simple example
class DB {
// Used to store your own instances
public static $instance = array();
public $conn;
// Private constructor to prevent external objects from instantiating objects
private function __construct($host, $username, $password, $dbname, $port) {
$this->conn = new mysqli($host, $username, $password, $dbname, $port);
}
// Static method, singleton access unified entrance
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);#Instantiation
}
return self::$instance[$key];
}
//query
public function query($ql) {
return $this->conn->query($sql);
}
// Private clone function to prevent external objects from being cloned
private function __clone() {}
// Release resources
public function __destruct(){
$this->conn->close();
}
}