PHP Singleton mode sample sharing
This article mainly shared a PHP singleton model of the example, design patterns of these flowers point of view of the basic is able to understand, of course, it is necessary to apply to the project is a certain practice, can not just know, or is very strong understand, one to the actual operation will not, nonsense will not say more
The singleton mode is primarily used for database connections, ensuring that the database has only one instance of a class and provides this instance to the entire system. This prevents new operations from consuming resources while avoiding too many connection information in the database.
There are three points: 1. There must be only one instance. 2. This instance must be created automatically. 3. This instance must be provided to the system as a whole.
The code is as follows:
Class mysql{
Privete static $instance;//Save Instance
The constructor is declared private, preventing the object from being created directly
Privete function __construct () {
Instantiation of
}
A singleton method that determines if it has been instantiated and instantiates only once
public static function getinstance () {
if (!isset (self:: $instance)) {
Self:: $instance = new self ();
}
Return self:: $instance;
}
Prevent cloning objects
Private Function __clone () {
Trigger_error ("not allow to clone.");
}
function Test () {
echo "Test";
}
}
$conn = Mysql::getinstance ();
$conn->test ();
?>
http://www.bkjia.com/PHPjc/957533.html www.bkjia.com true http://www.bkjia.com/PHPjc/957533.html techarticle PHP Singleton mode sample sharing this article mainly shared a PHP singleton pattern of examples, design patterns These flowers point of view of the basic is understandable, of course, to be very good use of the item ...