Home >Backend Development >PHP Tutorial >PHP object-oriented development - singleton mode
HP's global variables bring great flexibility to programming, but the unconstrained nature of global variables also brings great hidden dangers. The singleton pattern can be a good alternative to global variables.
Suppose there is a flower. Everyone who sees it will water the flower and then appreciate it.
class flower{ function __construct(){ echo date('Y-m-d H:i:s').'浇了花'; } public function look(){ return '一朵美丽的花'; } } $a=new flower();//将输出:2013-01-08 09:37:54浇了花 echo $a->look();//将输出:一朵美丽的花 $b=new flower();//将输出:2013-01-08 09:37:54浇了花 echo $b->look();//将输出:一朵美丽的
It can be seen that if there are more and more people, the flowers will be drowned sooner or later. What we need is that as long as the first person to see the flowers water the flowers, other people do not need to water the flowers.
class flower{ private static $instance; private function __construct(){ echo date('Y-m-d H:i:s').'浇了花'; } public static function getInstance(){ if(empty(self::$instance)){ self::$instance=new self(); } return self::$instance; } public function look(){ return '一朵美丽的花'; } } $a=flower::getInstance();//将输出:2013-01-08 09:52:43浇了花 echo $a->look();//将输出:一朵美丽的花 $b=flower::getInstance();//不会输出 echo $b->look();//将输出:一朵美丽的
The singleton mode is suitable for environments that only need to obtain the same instance, such as mysql database connections and other operations.
The above is the content of PHP object-oriented development - singleton mode. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!