PHP _ Singleton mode, instance code, and php instance code

Source: Internet
Author: User

PHP _ Singleton mode, instance code, and php instance code

If an object is instantiated in PHP, a new memory space will be opened up. When some businesses need to instantiate multiple objects, a large amount of memory will be occupied. This problem can be solved in singleton mode.

The instantiated object can be new directly, or through the constructor _ construct, destructor _ destruct, and clone _ clone in the class, we can privatize these three functions to prevent external entities from instantiating objects like this; then we can set a public static method called by class name. This is "three private and one public ".

 

The Code is as follows:

1 <? Php 2 3 // create a class first, next, call 4 class A {5 6} 7 8 // create Singleton class 9 One {10 // set A private static Property to save the object 11 private static $ obj; 12 13 // privatize the constructor 14 private function _ construct () {15} 16 17 // create a public static method, the static method is to call 18 static function getObj ($ className) directly through the class name) {19/** 20 * instanceof check whether an object belongs to this class 21 * if the instantiated object belongs to this class 22 */23 if (self ::$ obj instanceof $ className) {24 // return this object 25 return self: $ obj; 26} else {27 // if not, instantiate this object and return 28 self :: $ obj = new $ className; 29 return self: $ obj; 30} 31} 32 33 // private clone 34 private function _ clone () {35} 36} 37 38 // test 39 // no matter how many Class A is instantiated, only One object 40 $ one1 = One: getObj ('A') will be obtained '); 41 $ one2 = One: getObj ('A'); 42 $ one3 = One: getObj ('A'); 43 var_dump ($ one1 ); 44 var_dump ($ one2); 45 var_dump ($ one3 );

 

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.