This article mainly introduces the php single-state design mode (Singleton mode) instance. the single-state mode is mainly used to ensure that only one instance object exists in a class in the object-oriented programming design, for more information, see the single-state design mode:
1. meaning of the single-state design model:
The main function of the single-state mode is to ensure that only one instance object exists in a class in the object-oriented programming design. As the object creation mode, the singleton mode ensures that a class has only one instance, and the instance is self-instantiated and global to the entire system. It does not create instance copies, but returns a reference to the instance stored in the singleton class.
2. three key points of a single mode:
① A static member variable is required to save the unique instance of the class;
② Constructor and clone functions must be declared as private, so as to prevent external programs from losing the meaning of the Singleton mode;
③ A public static method (usually the getInstance method) must be provided to access this instance to return a reference of a unique instance.
The code is as follows:
<? Php
Class DB {
Private static $ obj = null; // declare a private, static member attribute $ obj
Private function _ construct () {// private constructor. the object can only be instantiated within the class.
Echo "connected to the database successfully
";
}
Public static function getInstance () {// This static method can be used to obtain objects of this class.
If (is_null (self: $ obj) // if $ obj in this class is empty, it indicates that it has not been instantiated.
Self: $ obj = new self (); // instantiate this class object
Return self: $ obj; // return the object of this class
}
Public function query ($ SQL) {// execute an SQL statement to complete database operations
Echo $ SQL;
}
}
$ Db = DB: getInstance (); // You can only use the static method getInstance () to obtain the database class objects.
$ Db-> query ("select * from user"); // access the members in the object
?>