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 (); An internal instantiation of an object in a class is assigned to a static property, and the first time the object is instantiated,

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

Return self:: $obj; Because there are judgments here, the instance object will not be repeated 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; The uname value of the $d object is output to the table because $e and $d point to the same object

Echo $e->uname; Will 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.