PHP Singleton mode definition and usage example-PHP source code

Source: Internet
Author: User
This article mainly introduces the definition and use of the PHP Singleton mode, and analyzes in detail the functions, definitions, usage methods, and related precautions of the php Singleton mode in combination with the specific database operation form, for more information about the definition and use of the PHP Singleton mode, the functions, definitions, usage, and precautions of the php Singleton mode are analyzed in detail based on the specific database operation type. For more information, see

This document describes how to define and use the PHP Singleton mode. We will share this with you for your reference. The details are as follows:

First, we will briefly introduce the Singleton mode. In Singleton mode, only one class instance exists in the application, and the second instance of this class can be generated without being affected by the external environment. Its advantages are as follows: if a single data operation instance exists in WEB development, it can reduce unnecessary resource consumption for connecting to the database, for large-scale software development, you can use a single instance to maintain the state of the program, so that different operations can be synchronized, because the single instance keeps occupying the memory, and there is no copy.

For PHP, the most common use case is to write a database operation class. However, to implement Singleton in PHP, there are the following rules:

1) the singleton class must have a declared constructor and be private.

2) the singleton class must have a static variable to store the class instance, so that this singleton class can have only one instance.

3) the singleton class must provide a static method for all other objects to apply this Singleton.

Why do we need to meet the above three conditions:

1) the singleton class can only be created once when the entire application is running. In addition, this kind of creation is completed by external calls, but by itself. Therefore, a singleton class instantiates itself, so its constructor must be private. No external object can create a copy of the singleton class again.

2) because a singleton class can only instantiate itself and provide its own instances for all external applications, there must be one inside the class for external access, it is the only constant access to the storage object. Therefore, we need to provide a static variable to store the instance object that the singleton class instantiates itself.

3) because the constructor of the singleton class is private, the singleton class must provide an external interface for the external environment to call the singleton class. Therefore, there must be a static method, it can initialize a singleton class or return a reference to an object of the singleton class.

A simple example:

Class DB {private $ _ link; // keep the static variable static $ _ instance of the singleton class; // private constructor private function _ construct () {$ this-> _ link = @ mysqli_connect (_ HOST __, _ USER __, _ PASSWORD __, _ DATABASE _); if (! ($ This-> _ link) {echo 'something wrong occurs on the database connection! ';}}// Prevents the singleton class from being cloned private function _ clone () {}// the public static function getInstance () interface for external access to the singleton class instance () {if (! (Self ::$ _ instance instanceof self) {self ::$ _ instance = new self ();} return self ::$ _ instance ;}}

Note that the _ clone () function defined above prevents the singleton class object from being cloned.

The following is a simple database operation example for your reference:

class DB {   /**    * the database connection    * @var   resource    * @access private    */   private $_link;   /**    * the static instance of single db    * @var   object    * @access static    */   static $_instance;   /**    * construct the single object    * @return null    * @access private    */   private function __construct(){       $this->_link = @mysqli_connect(__HOST__, __USER__, __PASSWORD__, __DATABASE__);       if(! ($this->_link)){          echo 'Something wrong occurs on the database connection!';         }   }   /**    * empty clone    * @return null    * @access private    */   private function __clone(){}   /**    * for other object to get the instance of db    * @return self::instance    * @access public    */   public static function getInstance(){       if(! (self::$_instance instanceof self)){          self::$_instance = new self();       }       return self::$_instance;   }   /**    * query    * @param  sql string    * @param  message string    * @return   resource    * @access public    */   public function query($sql,$message){       $result = @mysqli_query($this->$_link, $sql) or die($message . mysqli_error($this->$_link));       return $result;   }   /**    * mysqli_num_rows    * @param  result resource    * @return   int    * @access public    */   public function num($result){       return @mysqli_num_rows($result);   }   /**    * mysqli_fetch_array    * @param  result resource    * @return   array    * @access public    */   public function fetchArr($result){       return @mysqli_fetch_array($result);   }   /**    * mysqli_insert_id    * @return   int    * @access public    */   public function last_id(){       return @mysqli_insert_id($this->_link);      }   /**    * close the database connection    * @param  result resource    * @return   null    * @access public    */   public function close(){       @mysqli_close($this->_link);   }   /**    * fetch once result from the specific sql query    * @param  sql string    * @param  message string    * @return   array    * @access public    */   public function fetchArrOnce($sql, $message){       $result = $this->query($sql, $message);       $row = $this->fetchArr($result);       return $row;   }   /**    * fetch all results from the specific sql query    * @param  sql string    * @param  message string    * @return   array    * @access public    */   public function fetchArrMore($sql, $message){       $result = $this->query($sql, $message);       $moreRow = array();       while($row = $this->fetchArr($result)){          $moreRow[] = $row;       }       return $moreRow;   }   /**    * fetch the number of results from the specific sql query    * @param  sql string    * @param  message string    * @return   array    * @access public    */   public function fetchNum($sql, $message){       $result = $this->query($sql, $message);       $resultNum = $this->num($result);       return $resultNum;   }   /**    * mysqli_prepare    * @param  sql string    * @return   stmt object    * @access public    */   public function prepare($sql){       return @mysqli_prepare($this->_link, $sql);   }   /**    * mysqli_stmt_execute    * @param  stmt object    * @param  message string    * @return   bool    * @access public    */   public function stmt_execute($stmt, $message){       @mysqli_stmt_execute($stmt) or die($message . mysqli_error($this->_link));   }}

Usage:

define("__HOST__", "localhost");define("__USER__", "root");define("__PASSWORD__", "");define("__DATABASE__", "eee");$db = DB::getInstance();

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.