1<?PHP2 3 error_reporting(E_all|e_strict);4 5 classsingle{6 7 Public $hash;8 9 Static protected $ins=NULL;Ten One Final protected function__construct () {//final can be inherited and cannot be overridden (prevents subclasses from overriding the constructor method) A $this->hash =Mt_rand(1,9999); - } - the Static Public functiongetinstance () { - if(Self::$insInstanceof self) {//instanceof Determine if an object is an instance of a class - returnSelf::$ins; - } +Self::$ins=NewSelf (); - returnSelf::$ins; + } A } at - $s 1= Single::getinstance (); - $s 2= Single::getinstance (); - - Var_dump($s 1); - Var_dump($s 2); in - //son class inherits single class to classSonextendssingle{ + } - the $s 1= Son::getinstance (); * $s 2= Son::getinstance (); $ Panax Notoginseng Var_dump($s 1); - Var_dump($s 2);
Page output
Object (single) [1] Public ' hash ' = = int 9762object(Single) [1 ]public ' hash ' = int 9762object( Single) [1] public ' hash ' = = int 9762object(Single) [1] Public ' hash ' = int 9762
PHP Singleton Pattern Code snippet