PHP implementation of singleton mode_PHP tutorial

WBOY
Release: 2016-07-14 10:08:38
Original
996 people have browsed it

The singleton pattern ensures that there is only one instance of a class;

1. Static member variables save the only instance of the class
2. Declare the constructor and clone method as private to prevent new instances
3. Provide a public static method to access this instance and return a reference to the unique instance
class InstanceDemo
{
private static $_instance;//Static member variables save the only instance
private function __construct()//Constructor function
{
echo 'I am Construceted';
}
public static function GetInstance()
{
if(!isset(self::$_instance))
{
$c=__CLASS__;
                                                                                                                                                                                   
}
return self::$_instance;
}
//Override the __clone() method and disable cloning
private function __clone()
{
echo "clone prohibited";
}
function test()
{
echo("test instance");
}
}
//Call the static public method to get the only instance
$test = InstanceDemo::GetInstance();
$test->test();
//Cloneing is prohibited
$test_clone = clone $test;
?>

http://www.bkjia.com/PHPjc/477767.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/477767.htmlTechArticleThe singleton mode ensures that there is only one instance of a class; 1. Static member variables save the only instance of the class 2. Declaration The constructor and clone method are private to prevent new an instance 3 and provide a...
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