Php object-oriented development-Singleton mode

Source: Internet
Author: User
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 )!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.