Example of a single example pattern for PHP design Patterns

Source: Internet
Author: User
Tags php class


1. Define

A singleton pattern ensures that a class has only one instance, and instantiates it and provides this instance to the entire system globally. Instead of creating an instance copy, it returns a reference to an instance stored within a singleton class.

2. Solve the problem/use scenario

In the case of database applications, a single example pattern can be used to avoid the resources consumed by a large number of new operations.
If you need a class in your system to control some of the configuration information globally, then using a single example pattern can be easily implemented.

3. Key points in implementing a single case model

A static member variable that holds a unique instance of the class is required.
Constructors and cloning functions must be declared private to prevent the external program new class from losing the meaning of the single case schema.
You need to provide a static method that accesses this instance (typically the GetInstance method), and returns a reference to the instance.

4. Implementing Code Examples

<?php Class singleton {    private static  $instance;

    private  $conn;       private function __construct ()     {  

       $this->conn = mysql_connect (...); &NBSP;&NBSP;&NBSP;&NBSP}       private function __clone ()      {    }       public static function  getinstance ()     {        if  (!) ( Self:: $instance  instanceof self)         {   

         slef:: $instance  = new self ();         }         return  Self:: $instance; &NBSP;&NBSP;&NBSP;&NBSP}       public function getdbconnect ()   

  {        return  $this->conn; &NBSP;&NBSP;&NBSP;&NBSP}       public function selectdata ($sql)      {        //  $result  mysql_query ($sql, $this->

conn);         // while mysql_fetch_array ($result) ....   

&NBSP;&NBSP}   $db  = singleton::getinstance (); $db->selectdata ("Select * from user");

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.