Example of php Singleton mode. Php Singleton mode example: This article mainly shares an example of the php Singleton mode. the design pattern is easy to understand, of course, it is necessary to use the example of the php Singleton mode for sharing.
This article mainly shares an example of the php Singleton mode. the design mode is easy to understand, of course, it also requires some practice to make good use of the project. you can't just understand it, or you can understand it very well. once it comes to practice, you won't be able to do it.
The Singleton mode is mainly used for database connection. it ensures that a database class has only one instance and provides this instance to the entire system. This prevents the new operation from consuming resources and the too transaction connection information in the database.
There are three key points: 1. there must be only one instance. 2. the instance must be created automatically. 3. you must provide this instance to the entire system.
The code is as follows:
Class mysql {
Privete static $ instance; // Save the instance
// The constructor declares private to prevent direct object creation.
Privete function _ construct (){
// Instantiate
}
// Singleton method, which determines whether the instance has been instantiated and is only instantiated once
Public static function getInstance (){
If (! Isset (self: $ instance )){
Self: $ instance = new self ();
}
Return self: $ instance;
}
// Prevent cloned objects
Private function _ clone (){
Trigger_error ("not allow to clone .");
}
Function test (){
Echo "test ";
}
}
$ Conn = mysql: getInstance ();
$ Conn-> test ();
?>
Ghost This article mainly shares an example of the php Singleton mode. the design mode is easy to understand. of course, if you want to use it well...