Home  >  Article  >  Backend Development  >  PHP design patterns - singleton pattern

PHP design patterns - singleton pattern

WBOY
WBOYOriginal
2016-08-08 09:22:23846browse
It is easier to implement the singleton mode in PHP5. PHP5's access control for internal variables and functions of the class has been strengthened. By setting the DbConn::_construct() constructor to private, this class cannot be instantiated directly.

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.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn