Home  >  Article  >  Backend Development  >  Php object-oriented – singleton pattern_PHP tutorial

Php object-oriented – singleton pattern_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:19:48787browse

Php object-oriented – singleton pattern

Php object-oriented – singleton pattern

Guaranteed class has only one instance

1. How to solve the problem that a class can be instantiated infinitely?

New can be instantiated once. How to limit it? Users cannot use new unlimited times?

Private the constructor. All external new operations fail

class MySQLDB

{

private function __construct()

{

}

}

2. Once the constructor is privatized, it means that the class cannot be instantiated outside the class. But it can be instantiated within the class.

Add a public static method, call the method through the class, and perform new operations within the method.

class MySQLDB

{

private function __construct()

{

}

public static function getInstance()

{

return new MySQLDB;

}

}

$o = MySQLDB::getInstance();

At this time, when the user needs an object of this class, the code in the method will be executed. Therefore, we can limit the user's operation of obtaining the object by improving the logic within the method.

3. In the above method, use the following logic: make a judgment every time it is executed to determine whether the class has instantiated the object. If it has instantiated the object, directly return the instantiated object. If not instantiated, instantiate a new one and return.

How to judge?

Save this object when it is instantiated.

Example:

class MySQLDB

{

private static $instance;

private function __construct()

{

}

public static function getInstance()

{

if(!self::$instance instanceof self)

{

self::$instance= new self;

}

return self::$instance;

}

}

4. Cloning can also get new objects, so cloning needs to be restricted.

Private __clone() method

class MySQLDB

{

private static $instance;

private function __construct()

{

}

private function __clone()

{

}

public static function getInstance()

{

if(!self::$instance instanceof self)

{

self::$instance= new self;

}

return self::$instance;

}

}

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/871193.htmlTechArticlePhp object-oriented – singleton mode Php object-oriented – singleton mode guarantees that the class has only one instance 1. How to solve it Can a class be instantiated infinitely? New, you can instantiate it once...
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