The global variables of HP give a lot of flexibility to programming, but the unconstrained nature of global variables also brings great hidden dangers. Singleton mode can be a good substitute for global variables.
Suppose there is a flower, everyone will go to water the flowers, and then admire it.
Class Flower{function __construct () {echo date (' y-m-d h:i:s '). ' poured the flowers '; Public function look () {return ' a beautiful flower ';}} $a =new flower ();//Will output: 2013-01-08 09:37:54 poured the flowers echo $a->look ();//Will output: A beautiful flower $b=new flower ();//output: 2013-01-08 09:37:54 poured the flowers echo $b->look ();//Will output: a beautiful
It can be seen, if more people, flowers will be drowned sooner or later, what we need is, as long as the first to see the flowers are watering flowers, others do not need to water the flowers.
Class flower{ private static $instance; Private Function __construct () { echo date (' y-m-d h:i:s '). ' poured the flowers '; public static function getinstance () { if (the Empty (self:: $instance)) {self :: $instance =new-Self (); } Return self:: $instance; } Public function Look () { return ' a beautiful flower '; } } $a =flower::getinstance ();//Will output: 2013-01-08 09:52:43 The flowers were poured echo $a->look ();//Will output: A beautiful flower $b =flower:: GetInstance ();//will not output echo $b->look ();//output: a beautiful
The singleton mode is suitable for environments where only one instance of the same can be obtained, such as the connection and other operations of the MySQL database.
The above is the object-oriented development of PHP-Singleton mode of content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!