Php design mode-singleton mode, php design mode-Mode

Source: Internet
Author: User

Php design mode-singleton mode, php design mode-Mode

For a single instance, a class provides an instance through an interface and cannot create a new instance through new or clone.

The key to single-instance implementation is implemented through a static method getInstance. This method only returns the unique instance of this class. When this method is called for the first time, it creates an instance, put it in a private static variable. Next time, you only need to return the previously created instance to achieve the effect of Singleton.

1 class Log {2 static private $ instance = NULL; 3 4 private function _ construct () {5} 6 7 private function _ clone () {8} 9 10 function log ($ str) {11 echo $ str. PHP_EOL; 12} 13 14 static function getInstance () {15 if (self ::$ instance = NULL) {16 self ::$ instance = new Log (); 17} 18 return self: $ instance; 19} 20} 21 22 Log: getInstance ()-> log ("warning info"); 23 Log: getInstance () -> log ("error info"); 24 // the following error 25 new Log ();

Here, the constructor and the _ clone method are declared as private to prevent users from using new or clone to generate new instances.

 

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.