Home >Backend Development >PHP Tutorial >PHP design pattern singleton mode (single element mode)_PHP tutorial

PHP design pattern singleton mode (single element mode)_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 09:54:27949browse

php design pattern singleton mode (single element mode)

Single case mode:

As an object creation mode, the singleton mode ensures that a certain class has only one instance, instantiates itself and provides this instance globally to the entire system. It does not create a copy of the instance, but returns a reference to the instance stored internally in the singleton class.

(1). A static member variable that holds the only instance of the class is required: private static $_instance;

(2). Constructors and clone functions must be declared private to prevent external programs from creating new classes and thereby losing the meaning of the singleton mode:

private function __construct()

{

$this->_db = pg_connect('xxxx');

}

private function __clone()

{

}

(3). A public static method (usually the getInstance method) must be provided to access this instance, thereby returning a reference to the unique instance:

public static function getInstance()

{

if(! (self::$_instance instanceof self) )

{

self::$_instance = new self();

}

return self::$_instance;



}

Why use PHP singleton pattern?

1. PHP is mainly used in database applications, so there will be a large number of database operations in an application. Using the singleton mode can avoid a large number of resources consumed by new operations.

2. If a class is needed to globally control certain configuration information in the system, it can be easily implemented using the singleton mode.


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/997426.htmlTechArticlephp design pattern singleton mode (single element mode) Singleton mode: As an object creation mode, singleton The pattern ensures that there is only one instance of a class, and it instantiates itself and sends it to the entire...
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