Home > Backend Development > PHP Tutorial > php设计模式 Singleton(单例模式)_php技巧

php设计模式 Singleton(单例模式)_php技巧

WBOY
Release: 2016-05-17 09:17:53
Original
851 people have browsed it
复制代码 代码如下:

/**
* 单例模式
*
* 保证一个类仅有一个实例,并提供一个访问它的全局访问点
*
*/
class Singleton
{
static private $_instance = null;

private function __construct()
{
}

static public function getInstance()
{
if(is_null(self::$_instance)) {
self::$_instance = new Singleton();
}
return self::$_instance;
}

public function display()
{
echo "it is a singlton class function";
}
}

// $obj = new Singleton(); // 声明不能成功
$obj = Singleton::getInstance();
var_dump($obj);
$obj->display();

$obj1 = Singleton::getInstance();
var_dump(($obj === $obj1));
Related labels:
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