Php Singleton mode, php Mode
Today, when I was learning php object-oriented, I saw an object-oriented interview question.
The question is as follows:
++ Interview questions ++
Use the singleton design mode method to meet the following requirements:
Use the PHP5 code writing class to achieve that only one unique database connection can be obtained for each access to the database. The detailed code for connecting to the database is ignored. Write the main logic code.
++
The Singleton mode has several key points:
1. class constructor must be marked as private (Access Control: to prevent external code from creating objects through the new operator) to be instantiated in other classes. It can only be instantiated in the class itself.
Private fcuntion _ construc ()
2. A private static member variable is used to save the class instance.
Private static $ ins; // $ ins is used to save the instance of this class.
3. You have a static method to access this class instance (the getInstance () method is often used to instantiate the singleton class, And the instanceof operator can detect whether the class has been instantiated)
4. Create a private _ clone method to prevent objects from being copied.
Why?
1. php applications mainly lie in database applications. Therefore, a large number of database operations exist in an application. Using the singleton mode can avoid the resources consumed by a large number of new operations.
2. If you need a class in the system to globally control some configuration information, you can easily implement it using the singleton mode. For details, refer to the FrontController section of ZF.
3. In a page request, debugging is easy. Because all the code (such as database operation db) is concentrated in a class, we can set hooks in the class and output logs, this avoids var_dump and echo everywhere.
The final answer code is as follows:
<? Php class Mysql {private static $ instance = null; private $ conn; // constructor, which is set to private. The private function _ construct (argument) of the object instance cannot be obtained through new) {$ conn = mysql_connect ("localhost", "root", "root");} // obtain the instance method public static function getInstance () {if (! Self: $ instance instanceof self) {self: $ instance = new self;} return self: $ instance;} // prohibit cloning private function _ clone () {}}// get object $ db = Mysql: getInstance ();?>
Here we will make a memorandum.
<? Phpclass Mysql {privatestatic $ instance = null; private $ conn; // constructor, which is set to private. Obtaining the object instance privatefunction _ construct (argument) through new is not allowed) {$ conn = mysql_connect ("localhost", "root", "root");} // obtain the instance method publicfunction getInstance () {if (! Self: $ instance instanceofself) {self: $ instance = newself;} returnself: $ instance ;}// prohibit cloning privatefunction _ clone () {}}// get object $ db = Mysql: getInstance ();?>