One instance in PHP Singleton mode and one instance in PHP Mode

Source: Internet
Author: User

One instance in PHP Singleton mode and one instance in PHP Mode

This article does not necessarily explain the PHP Singleton mode! I just want to give an instance, so that I can better understand the singleton mode through an instance! This is for your reference only!


Singleton: It can be simply understood that a class can only instantiate a single object, but not multiple objects!

Class e {

Public $ uname;

Static $ obj = NULL; // defines a static property.

Private function _ construct (){ // Use the private attribute before the constructor. The object cannot be instantiated outside the class,

// It cannot be $ a = new e ();

} // If you want to use the new keyword to instantiate an object, the constructor will be called,

// This function has been modified to private. An error is returned when the new keyword is used to instantiate an object.

Static function getObj (){

If (is_null (self: $ obj )){

Self: $ obj = new e (); // The static attribute is assigned to the instantiated object inside the class. When the object is instantiated for the first time,

} // $ Obj is assigned a value. When an object is instantiated later,

Return self: $ obj; // because of this judgment, the instance object will not be repeated and will only be instantiated once;

} // When an object is instantiated for multiple times, it only assigns the object reference value to the variable and does not instantiate the object again.

}

$ D = e: getObj ();

$ D-& gt; uname = 100;

Echo $ d-> uname; // 100

$ E = e: getObj ();

$ E-& gt; uname = 200;

Echo $ d-> uname; // the output value is 200. The uname value of the $ d object is also in this table, because $ e and $ d point to the same object.

Echo $ e-> uname; // output 200


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.