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

PHP design patterns - singleton pattern

WBOY
Release: 2016-08-08 09:22:23
Original
893 people have browsed it
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.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template