PHP4でシングルトン
PHP4でシングルトンなクラスの設計をしていて、サブクラスを作ってふがふが…って話が出てきた。
シングルトンってサブクラス作れないだろうと思いきや、PHP4だとコンストラクタもpublicだしサブクラス作れちゃうのでした。
▼ 実行結果
とりあえず、こんな感じかな?
サブクラスのgetInstanceの実装はかなりイケてないんだけど、クラス名がとれないっぽいので。
う〜ん。PHP4のstaticの挙動はかなりアレだな。
シングルトンってサブクラス作れないだろうと思いきや、PHP4だとコンストラクタもpublicだしサブクラス作れちゃうのでした。
- class AbstractSingle
- {
- var $value;
- function AbstractSingle () {}
- function & getInstance () {
- static $instance;
- if ($instance === NULL) {
- $instance = new AbstractSingle();
- }
- return $instance;
- }
- function setValue ($value) {
- $this->value = $value;
- }
- function getValue () {
- return $this->value;
- }
- }
- class SingleA extends AbstractSingle
- {
- function SingleA () {
- parent::AbstractSingle();
- }
- function & getInstance () {
- static $instance;
- if ($instance === NULL) {
- $instance = new SingleA();
- }
- return $instance;
- }
- }
- class SingleB extends AbstractSingle
- {
- function SingleB () {
- parent::AbstractSingle();
- }
- function & getInstance () {
- static $instance;
- if ($instance === NULL) {
- $instance = new SingleB();
- }
- return $instance;
- }
- }
- $a =& SingleA::getInstance();
- $a->setValue('A');
- $b =& SingleB::getInstance();
- $b->setValue('B');
- print $a->getValue();
- print "\n";
- print $b->getValue();
- print "\n";
- $a2 =& SingleA::getInstance();
- $a2->setValue('A2');
- print $a->getValue();
- print "\n";
- print $b->getValue();
- print "\n";
▼ 実行結果
A
B
A2
B
とりあえず、こんな感じかな?
サブクラスのgetInstanceの実装はかなりイケてないんだけど、クラス名がとれないっぽいので。
う〜ん。PHP4のstaticの挙動はかなりアレだな。
| ホーム |



