Hp's global variables bring great flexibility to programming, but the unbinding nature of global variables also brings great risks. The Singleton mode can effectively replace global variables. Hp's global variables bring great flexibility to programming, but the unbinding nature of global variables also brings great risks. The Singleton mode can effectively replace global variables.
If there is a flower, everyone will see it and then appreciate it.
Class flower {function _ construct () {echo date ('Y-m-d H: I: s '). 'watered flow';} public function look () {return 'a beautiful flow' ;}}$ a = new flower (); // output: 09:37:54 pouring flowers echo $ a-> look (); // will output: a beautiful flower $ B = new flower (); // will output: 09:37:54 pouring flowers echo $ B-> look (); // output: a beautiful
It can be seen that if there are more and more people and the flowers are drowned early or late, what we need is that as long as the first person sees the flowers, they don't need to be watered.
Class flower {private static $ instance; private function _ construct () {echo date ('Y-m-d H: I: s '). 'watered flow';} public static function getInstance () {if (empty (self: $ instance) {self: $ instance = new self ();} return self: $ instance;} public function look () {return 'a beautiful flow' ;}}$ a = flower: getInstance (); // output: 09:52:43 pouring flowers echo $ a-> look (); // output: a beautiful flower $ B = flower: getInstance (); // no echo $ B-> look () will be output; // A beautiful
The Singleton mode is applicable to environments that only require the same instance, such as mysql database connection and other operations.
The above is php object-oriented development-Singleton mode. For more information, see PHP Chinese Web (www.php1.cn )!