This article mainly shares an example of a PHP single example pattern, design patterns These flower point of mind Basic is able to understand, of course, want to very good application to the project is also need a certain practice, can not just know, or say is very strong understand, one to the actual operation is not, nonsense will not say more
The singleton pattern is primarily used for database connections, ensuring that a database class has only one instance, and provides this instance to the entire system. This prevents the new operation from consuming resources while avoiding too many connection information in the database.
The main points are three: 1. Must have only one instance. 2. This instance must be created automatically. 3. This example must be provided to the system as a whole.
The code is as follows:
?
Class mysql{
Privete static $instance;//Save Instance
Constructors are declared private to prevent the creation of objects directly
Privete function __construct () {
Instantiation of
}
Single-instance method to determine if it has been instantiated, only once
public static function getinstance () {
if (!isset (self:: $instance)) {
Self:: $instance = new self ();
}
Return self:: $instance;
}
Prevent cloning of objects
Private Function __clone () {
Trigger_error ("not allow to clone.");
}
function Test () {
echo "Test";
}
}
$conn = Mysql::getinstance ();
$conn->test ();
?>