<?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();
return new Singleton(""):
は
self::$instance = new である必要がありますSingleton(""):
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();
コードを 1 つ変更するだけです。シングルトンを $instance に入れるのを忘れています
public static function getInstance(){ if(self::$instance==null){ self::$instance= new Singleton(""); } return self::$instance; }