This time to everyone to bring PHP singleton mode use case, PHP single-case mode of attention to use what, the following is the actual case, together to see.
In this paper, we describe the principle and implementation of the single-case pattern of PHP design pattern. Share to everyone for your reference, as follows:
First, what is a singleton mode
As the object's creation mode, Singleton mode ensures that a class has only one instance and provides access to the global instance externally. Instead of creating an instance copy, it returns a reference to the instance stored inside the singleton class.
Two, PHP single case model three elements
1. You need a static member variable that holds a unique instance of the class.
2. Constructors and clone functions must be declared private to prevent external programs from creating or copying instance replicas.
3. A public static method that accesses this instance must be provided to return a reference to the unique instance.
Third, why use a singleton mode
The benefits of using singleton patterns are large, as is the case with database operations. If you do not use a singleton mode, when a large number of database operations in the program, each time to perform a new operation, each time consumes a lot of memory resources and system resources, and each open and close the database connection is a great test and waste of the database. Using singleton mode, you only need to instantiate one time, do not need to do new operations every time, greatly reducing the cost of resources.
Iv. example of a singleton pattern
Here is an example of a database operation
<?php/*** Singleton mode **/class db{ //Save global instance private static $instance; Database connection handle private $db; Database connection parameter const HOSTNAME = "127.0.0.1"; Const USERNAME = "root"; Const PASSWORD = "root"; Const DBNAME = "TestDB"; Privatization constructor to prevent external instantiation of object Private Function construct () { $this->db = Mysqli_connect (Self::hostname, Self::username, self ::P assword,self::D bname); } Privatization cloning function to prevent external cloning of objects private Function clone () { } //Singleton Access Unified Portal Public static function getinstance () { if (!) ( Self:: $instance instanceof Self) {self :: $instance = new self (); } Return self:: $instance; } Database query operation public function GetInfo () { $sql = ' select * from TESTTB '; $res = Mysqli_query ($this->db, $sql); while ($row = Mysqli_fetch_array ($res)) { echo $row [' Testcol ']. ' <br/> '; } Mysqli_free_result ($res); }} $mysqli = Db::getinstance (); $mysqli->getinfo ();? >
Believe that you have read the case of this article you have mastered the method, more exciting please pay attention to the PHP Chinese network other related articles!
Recommended reading:
PHP generates two-dimensional code poster case study
Phpexcel Modification Steps