您好,欢迎访问一九零五行业门户网

关于单例模式的问题~

name = $name; } public static function getinstance(){ if(self::$instance==null){ return new singleton(); } return self::$instance; } public function printstring(){ echo hello,this is printstring().
; } public function setname($name){ $this->name = $name; } public function getname(){ echo the name is .$this->name.
; }}$class = singleton::getinstance();$class->printstring();$class->setname(jack);$class->getname();$class2 = singleton::getinstance();$class2->getname();

为何 $class2->getname() 输出的 name 也为空呢?
回复讨论(解决方案) return new singleton():
应为
self::$instance = new singleton():
如果 return new singleton(): 的话就直接返回了另一个实例
就不是单例模式了
name = $name; } public static function getinstance(){ if(self::$instance==null){ return new singleton(); } return self::$instance; } public function printstring(){ echo hello,this is printstring().
; } public function setname($name){ $this->name = $name; } public function getname(){ echo the name is .$this->name.
; }}$class = singleton::getinstance();$class->printstring();$class->setname(jack);$class->getname();$class2 = singleton::getinstance();$class2->getname();

为何 $class2->getname() 输出的 name 也为空呢?
谢谢楼上~
只要改一处代码即可:你忘了把单例放入$instance
public static function getinstance(){ if(self::$instance==null){ self::$instance= new singleton(); } return self::$instance; }
其它类似信息

推荐信息