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.
Copy Code code 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 ();
?>