An example of PHP's singleton pattern

Source: Internet
Author: User

This article does not necessarily improve the interpretation of PHP singleton mode! Just to give an example, the purpose is to let me through an instance can deepen the understanding of the singleton mode! Here, for reference only!


Singleton: It is simple to understand that a single object can only be instantiated through a class, and multiple objects cannot be instantiated!

Class E {

Public $uname;

static $obj = NULL; //Define a static property

Private Function __construct () { //Use the private property before constructing the method, in order to not instantiate the object outside the class.

That cannot $a=new e ();

} //If you want to instantiate an object using the New keyword, the constructor is called.

The function has been decorated as private, and an error occurs when instantiating an object using the New keyword.

static function Getobj () {

if (Is_null (self:: $obj)) {

Self:: $obj = new E (); //The object is assigned to a static property in the inner instantiation of the class, and the first time the object is instantiated,

} //$obj will be assigned, and when the object is instantiated later,

Return self:: $obj; // the instance object is not repeated because there is a judgment here The object is instantiated only once;

} // instantiating an object more than once, simply assigning the object's reference to the variable and not instantiating the object again

}

$d = E::getobj ();

$d->uname = 100;

Echo $d->uname; 100

$e = E::getobj ();

$e->uname = 200;

Echo $d->uname; //Outputs a maximum of $d the uname value of the object is also the table because $e and $d point to the same object

Echo $e->uname; //Will output


An example of PHP's singleton pattern

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.