PHP design mode single-instance pattern code, PHP design mode
PHP design pattern of a single example model for your reference, the specific content as follows
<?php/** * PHP design mode singleton mode */class fruit{private static $instanceMap = Array (); Protected getter for singleton instances protected static function Getsingleton ($className) {//Guaranteed singleton mode and cannot be from the controller instance and Clone if (!isset (self:: $instanceMap [$className])) {$object = new $className; Make sure this object inherit from Singleton if ($object instanceof Fruit) {self:: $instanceMap [$classNa Me] = $object; Var_dump ($object); } else {throw singletonexception ("Class ' $className ' do not inherit from singleton!"); }} return Self:: $instanceMap [$className]; }//protected constructor to prevent outside instantiation protected function __construct () {}//denie cloning of Singleton objects Public final function __clone () {trigger_error (' It's impossible to clone Singleton ', E_user_err OR); }} class Apple extends fruit{protected $rndId; Public Function __construct () {$thisRndid = rand (); } public Function Whatami () {echo ' I am a Apple ('. $this->rndid. ')
'; } public static function getinstance () {//echo get_class (); Return Fruit::getsingleton (Get_class ()); }} class Greenapple extends apple{public Function Whatami () {echo ' I am a greenapple ('. $this->rndid. ')
'; } public static function getinstance () {return Fruit::getsingleton (Get_class ()); }} $apple 1 = apple::getinstance (); Var_dump ($apple 1); $apple 2 = greenapple::getinstance (); $apple 1->whatami ()//should echo ' I am a Apple (some number) $apple 2->whatami ();//should Echo ' I am a greenapple (s ome number) $apple 1 = apple::getinstance (); $apple 2 = greenapple::getinstance (); Guaranteed Singleton mode $apple 1->whatami ();//should Echo ' I am a Apple (same number as above) $apple 2->whatami ();//should Echo ' I am a greenapple (same number as above)//$a = Clone $apple 1;//This should fail//$b = Clone $apple 2;//this should F Ail
The above is the whole content of this article, I hope that you learn PHP programming help.
http://www.bkjia.com/PHPjc/1135010.html www.bkjia.com true http://www.bkjia.com/PHPjc/1135010.html techarticle PHP design mode of the single-case pattern code, PHP design mode PHP design mode of the Singleton model example, for your reference, the specific content as follows PHP/** * PHP design mode single-case mode */clas ...