PHP design mode single-instance mode

Source: Internet
Author: User

directly on the code;

<?PHPclasssinglecase{//declaring private variables  Private $name; //declaring static variables   Public Static $interest; //declaring private constructors to prevent external instantiation  Private function__construct () {//code ...  }  //External Call entry (static method)   Public Static functionenterance () {//determine if a $interest has a value    if(!self::$interest) Self::$interest=Newsinglecase (); //returns the current object    returnSelf::$interest; }  //single-mode test method to determine if internal methods can be successfully invoked   Public functionSetName ($n)  {    $this->name =$n; }   Public functiongetname () {return $this-name; }}//call the static method directly from the backdoor$a= Singlecase::enterance ();//passing values to the SetName function$a->setname ("singleton mode is complete."));Echo $a-getname ();$b= Singlecase::enterance ();if($a==$b) {  Echo"</br> is the same instance";} Else {  Echo"Not the same instance";}

Why use static member properties to store instances?

因为只有第一次实例化的时候才赋值、以后都直接给出静态实例。

PHP design mode single-instance mode

Related Article

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.