php单例模式没搞懂
本文介绍了php单例模式没搞懂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
class test
{
private static $instance;
private function __construct()
{
echo 2;
}
public static function getInstance()
{
if( !( self::$instance instanceof self ) )
{
echo 1;
self::$instance =new self();
}
return self::$instance;
}
private function __clone()
{
}
}
test::getInstance(); //12
self::$instance =new self() 这里实例存不进静态私有变量里面啊,怎么实现单例?还是我哪里写错了?
解决方案
其实吧,你的代码没问题啊。。。
class test
{
private $props = [];
private static $instance;
private function __construct()
{
echo 2;
}
public static function getInstance()
{
if( !( self::$instance instanceof self ) )
{
echo 1;
self::$instance =new self();
}
return self::$instance;
}
private function __clone()
{
}
public function setProp($key, $val)
{
$this->props[$key] = $val;
}
public function getProp($key)
{
return $this->props[$key];
}
}
$a = test::getInstance(); //12
$b = test::getInstance(); //没有输出
$a->setProp("name", "zhangsan");
echo $b->getProp("name"); //zhangsan
改成这样,不知道你能理解了不。。。
这篇关于php单例模式没搞懂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文