欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

关于单例模式的问题~

程序员文章站 2022-05-30 22:36:41
...
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;    }