PHP Single Example mode detailed
The concept of a single case pattern
A single example pattern is a design pattern in which a class has only one object instance in the entire application. Specifically, as an object creation, the singleton pattern ensures that a class has only one instance, and instantiates it itself 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.
Characteristics of a single case model
The main feature of the single case model is "three private one":
A private static member variable is required to hold a unique instance of the class
Constructors must be declared private to prevent an external program from creating an object that loses the meaning of a single instance
The clone function must be declared private to prevent the object from being cloned
A public static method (usually named getinstance) that accesses this instance must be provided to return a reference to a unique instance.
Reasons and scenarios for using a single case pattern
In most PHP applications there will be a large number of database operations, if you do not use the single example mode, that each time the new operation, but each time new will consume a lot of system resources and memory resources, and each open and close the database is a great test of the database and waste. Therefore, a single example pattern is often used in database operations classes.
Similarly, if you need a class in your system to control some configuration information globally, then using a single example pattern can be a convenient implementation.
PHP Single Example mode implementation
Here is a PHP single example schema to implement the database Operation class framework
constdb_host= ' localhost ';
To save a private static variable for an instance
Constructors and cloning functions are declared as private
Privatefunction__construct () {
$this->_db=mysql_connect ();
Privatefunction__clone () {
To access the public static method of an instance
Publicstaticfunctiongetinstance () {
if (!) ( Self::$_instanceinstanceofself)) {
Self::$_instance=newself ();
if (self::$_instance===null) {
Self::$_instance=newdb ();
Publicfunctionfetchall () {
Publicfunctionfetchrow () {
Gets the reference of an instance outside of the
|
Thank you for reading, I hope to help you, thank you for your support for this site!
Original link: http://www.manongjc.com/article/557.html
!--? PHP class db{const db_host= ' localhost '; const db_name= '; const db_user= '; const db_pwd= '; private $_db;//Save private static variable $_instance for instance; Both the constructor and the clone function are declared to be private privately function __construct () {//$this--->