The singleton pattern ensures that there is only one instance of a class that is instantiated and made available to the entire system.

Singleton is a common design pattern. In computer systems, thread pools, caches, log objects, dialog boxes, printers, database operations, and video card drivers are often designed as singleton.

The singleton pattern has the following three characteristics:

1. There can be only one instance.

2. You must create this instance yourself.

3. You must provide this instance to other objects.

So why use the PHP singleton?

A major application of PHP is the scenario where the application program deals with the database. There will be a large number of database operations in an application. Singleton mode can avoid a large number of new operations when the database handle connects to the database. Because each new operation consumes system and memory resources.

Singleton mode is divided into three types: lazy singleton, hungry singleton and registered singleton.

Lazy singleton:

<? PHP // lazy singleton class. Class Singleton {// create a static private variable to hold the class; Private function __clone(){} static public function __clone(){ GetInstance () {// check if $instance is the Singleton object, if (! self::$instance instanceof self) { self::$instance = new self(); } return self::$instance; } public function test() {echo "I am a singleton "; } } $sing = Singleton::getInstance(); $sing->test(); $sing2 = new Singleton(); //Fatal error: Uncaught Error: Call to private Singleton::__construct() from invalid context in $sing3 = clone $sing; //Fatal error: Uncaught Error: Call to private Singleton::__clone() from contextCopy the code

PHP does not support hunchy-style singletons because PHP does not support assigning values of non-primitive types to member variables of a class when it is defined. Expressions, new operations, and so on

<? PHP // Hungry singleton class. $instance = new self(); private static $instance = new self(); private static $instance = new self(); //Fatal error: Constant expression contains invalid operations in /usercode/file.php on line 3 private function __construct() { } public static function getInstance() { return self::$instance; } } $test = Test::getInstance() ? >Copy the code

Reference: www.cnblogs.com/hxun/p/1184…