Home >Backend Development >PHP Tutorial >PHP singleton mode example sharing_PHP tutorial

PHP singleton mode example sharing_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:06:40955browse

Sharing examples of PHP singleton pattern

This article mainly shares an example of PHP singleton pattern. The basic considerations of design patterns are understandable. Of course, if you want to apply it well to the project, you also need a certain amount of practice. You can’t just know and understand it, or say that you are very powerful and understand it. When it comes to actual operation, it won’t work. I won’t talk nonsense

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.

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(){
// Instantiate
}
//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 ();
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/957533.htmlTechArticlephp singleton mode example sharing This article mainly shares an example of php singleton mode, design patterns and so on It is understandable to put some thought into it. Of course, if you want to apply it well...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn