Singleton
わからないのですが・・・
class Singleton { function Singleton() { print "インスタンスを生成しました。\n"; } function &getInstance() { static $instance; if ($instance == null) { $instance = new Singleton(); } return $instance; } } $obj1 =& Singleton::getInstance(); $obj2 =& Singleton::getInstance(); if ($obj1 === $obj2) { print "obj1とobj2は同じインスタンスです。\n"; } else { print "obj1とobj2は違うインスタンスです。\n"; }
これを実行すると、
インスタンスを生成しました。 インスタンスを生成しました。 obj1とobj2は同じインスタンスです。
となります。Windows版の4.3.11です。
2回目の$instanceにはSingletonクラスのインスタンスが入っているので、nullじゃないと思うんですが、if文内が実行されます。なぜ???
クラスにプロパティがない場合、(object = = null) って true になるんですね・・・
class Singleton { function Singleton() { print "インスタンスを生成しました。\n"; } function &getInstance() { static $instance = null; if (is_null($instance)) { $instance = new Singleton(); } return $instance; } }
にしました。