PHP singleton mode example sharing_PHP tutorial

WBOY
Release: 2016-07-13 10:06:40
Original
891 people have browsed it

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...
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!