So that the class can not create objects in the outside world//Let outsiders make an object, do a static method to return the object//In the class by letting the static variable control return object can only be one.
The main points of the singleton pattern are three:
One is that a class can have only one instance;
The second is that it must create this instance on its own;
Thirdly, it must provide this instance to the whole system on its own.
Why use PHP singleton mode
1. The application of PHP is mainly in the database application, there will be a large number of database operations in an application, when the use of object-oriented development, if the use of Singleton mode, you can avoid a large number of new operations consumed by the resources, but also reduce the database connection so it is not easy to appear too many Connections situation.
2. If a class is needed in the system to control some configuration information globally, it can be easily implemented using singleton mode. This can be see the Frontcontroller section of the Zend Framework.
3. In a page request, it is easy to debug, because all the code (such as database Operation class DB) is concentrated in a class, we can set the hooks in the class, output the log, so as to avoid var_dump everywhere, echo.
Class cat{public $name; Private Function __construct () { } static $temp; static function New_ob () { if (Empty (self:: $temp)) {self :: $temp = new Cat (); } Return self:: $temp; } function speak () { return "meow Meow"; }} $mao = new Cat ()//If no cat is created, then equal to the new xxx, if any, directly equals. The purpose of reaching the limit. $mao;//if (Empty ($mao)) {// $mao = new Cat ();//}// $xxx = $mao; $mao = Cat::new_ob (); $mao 2 = Cat::new_ob ();// Change the name of the cat to 1, and the name of the 2 cat is the name of the 1 cat. This is a singleton. $mao->name = "py";
2. Simple Factory mode
① abstract base class: Some methods of defining abstractions in classes to implement in subclasses
② inherits from the subclass of the abstract base class: Implementing an abstract method in a base class
③ Factory class: Used to instantiate all the corresponding sub-classes
abstract class jsq{public $a; Public $b; function Yunsuan () {}}//This is the extended class Jiafa extends jsq{function Yunsuan () {//parent::yunsuan ();//Todo:c Hange the autogenerated stub return $this->a+ $this->b; }}class Jianfa extends jsq{function Yuansuan () {return $this->a-$this->b; }}class factory{static function Create ($x) {switch ($x) {case "+": return new Jiafa (); Break Case "-": Return new Jianfa (); Break }}}//$j 1 = new Jiafa (),//$j 1->a = 1;//$j 1->b = 2;//$j 1->yunsuan ();//try to avoid instantiating objects and obtain them using static methods. $JF = factory::create ("+"), $jf->a = 1; $JF->b = 2;echo $jf->yunsuan ();