An example of a single example pattern in PHP

Source: Internet
Author: User
Tags object reference

This article is not necessarily perfect for the explanation of the PHP single example mode! Just give an example, the purpose is to let myself through an example can deepen the understanding of the single case mode! Here, for reference only!


Single example: It is simple to understand that a class can only instantiate a single object and cannot instantiate multiple objects!

Class E {

Public $uname;

static $obj = NULL; Define a static property

Private Function __construct () { ///The private property is used before the method is constructed in order to not instantiate the object outside of the class.

That cannot $a=new e ();

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

This function has been decorated as private, and an error is made when instantiating the object with the New keyword.

static function Getobj () {

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

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

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

Return self:: $obj; Because there's a judgment here. The instance object will only instantiate the object once;

///Multiple objects are instantiated, only the object's reference is assigned to the variable, the object is not instantiated again

}

$d = E::getobj ();

$d->uname = 100;

Echo $d->uname; 100

$e = E::getobj ();

$e->uname = 200;

Echo $d->uname; Output, the uname value of the $d object is also in 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.