Sharing of php singleton mode examples, sharing of php mode examples
The singleton mode is mainly used for database connections, ensuring that there is only one instance of a class in the database, and providing this instance to the entire system. This prevents the new operation from consuming resources and avoids too many connection information appearing in the database.
There are three main points: 1. There must be only one instance. 2. This instance must be created automatically. 3. This instance must be provided to the entire system.
Copy code The code is as follows:
class mysql{
private static $instance ;//Save instance
//The constructor is declared as private to prevent direct creation of objects
private function __construct(){
// instance <化>
}
//Single case method, determine whether it has been instantiated, and only instantiate it 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.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/957122.htmlTechArticlephp singleton mode example sharing, php mode example sharing singleton mode is mainly used for database connections, ensuring a database A class has only one instance, and provides this implementation to the entire system...