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