PHP singleton mode sample sharing, PHP pattern sample sharing
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.
Copy the Code code 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/957122.html www.bkjia.com true http://www.bkjia.com/PHPjc/957122.html techarticle PHP Singleton mode sample sharing, PHP mode sample sharing singleton mode is mainly used in the database connection, to ensure that the database has only one instance of a class, and to provide this reality to the entire system ...