Use a combination of static methods and static variables to maintain this instance, and set the constructor to be private to prevent direct instantiation of the class and create an instance. The code is as follows:
class DbConn {
/**
* static property to hold singleton instance
*/
static $instance = false;
/**
* constructor
* private so only getInstance() method can instantiate
* @return void
*/
private function __construct() {}
/**
* factory method to return the singleton instance
* @return DbConn
*/
public function getInstance() {
if (!DbConn::$instance) {
DbConn::$instance = new DbConn;
}
return DbConn::$instance;
}
}
The above has introduced the PHP design pattern - singleton pattern, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.