An object-oriented development of PHP--Singleton mode

Source: Internet
Author: User
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)!

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.