Home > Backend Development > PHP Tutorial > 关于单例模式的问题~

关于单例模式的问题~

WBOY
Release: 2016-06-20 12:49:35
Original
987 people have browsed it

<?php/** * Created by PhpStorm. * User: Administrator * Date: 2015/8/30 * Time: 12:53 */class Singleton{    private static $instance = null;    private function __construct($name){        $this->name = $name;    }    public static function getInstance(){        if(self::$instance==null){            return new Singleton("");        }        return self::$instance;    }    public function printString(){        echo "hello,this is printString()"."<br/>";    }    public function setName($name){        $this->name = $name;    }    public function getName(){        echo "The name is ".$this->name."<br/>";    }}$class = Singleton::getInstance();$class->printString();$class->setName("jack");$class->getName();$class2 = Singleton::getInstance();$class2->getName();
Copy after login
Copy after login


为何 $class2->getName() 输出的 name 也为空呢?


回复讨论(解决方案)

return new Singleton(""):
应为
self::$instance = new Singleton(""):

如果 return new Singleton(""): 的话就直接返回了另一个实例
就不是单例模式了

<?php/** * Created by PhpStorm. * User: Administrator * Date: 2015/8/30 * Time: 12:53 */class Singleton{    private static $instance = null;    private function __construct($name){        $this->name = $name;    }    public static function getInstance(){        if(self::$instance==null){            return new Singleton("");        }        return self::$instance;    }    public function printString(){        echo "hello,this is printString()"."<br/>";    }    public function setName($name){        $this->name = $name;    }    public function getName(){        echo "The name is ".$this->name."<br/>";    }}$class = Singleton::getInstance();$class->printString();$class->setName("jack");$class->getName();$class2 = Singleton::getInstance();$class2->getName();
Copy after login
Copy after login


为何 $class2->getName() 输出的 name 也为空呢?


谢谢楼上~

只要改一处代码即可:你忘了把单例放入$instance

    public static function getInstance(){        if(self::$instance==null){            self::$instance= new Singleton("");        }        return self::$instance;    }
Copy after login

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