PHP 5.3 'te bir Singleton temel sınıf oluşturma

0 Cevap php

Straight to the point: I've got two singleton classes, both inheriting their singleton nature from a super-class. I initialize some properties on the first singleton, and then have the second singleton retrieve the instance of the first one. That instance, however, does not seem to be the one I initialized in the first place. Some example code might help to explain this:

İlk olarak, tekil doğa sağlayan süper-sınıfı, (PHP 5.3 veya üstü gerektirir):

class Singleton {

    protected static $instance;

    protected function __construct() { }

    final private function __clone() { }

    public static function getInstance() {
        if (!(static::$instance instanceof static)) {
            static::$instance = new static();
        }
        return static::$instance;
    }

}

Sonra bir değer taşıyan ilk tekiz var:

require_once('Singleton.php');

class SingletonA extends Singleton {

    protected $value;

    public function SingletonA() {
        $this->value = false;
    }

    public function getValue() {
        return $this->value;
    }

    public function setValue($value) {
        $this->value = $value;
    }

}

Sonra ilk tekiz başvuran ikinci tekil:

require_once('Singleton.php');
require_once('SingletonA.php');

class SingletonB extends Singleton {

    public function getValue() {
        return SingletonA::getInstance()->getValue();
    }

}

Şimdi bu başarısız nasıl gösterir test için:

require_once('SingletonA.php');
require_once('SingletonB.php');

SingletonA::getInstance()->setValue(true);

echo (SingletonA::getInstance()->getValue()) ? "true\n" : "false\n";
echo (SingletonB::getInstance()->getValue()) ? "true\n" : "false\n";

Test şu çıktıyı verir:

true
false

Açıkçası, test kodu referanslar aynı örneği SingletonB örnek referanslar olmadığını SingletonA örneği. Kısacası, SingletonA ben olmak gerekiyor gibi tek değildir. Bu nasıl mümkün olur? Ve bana gerçek bir singleton vererek, bu davranışı gidermek için ne sihirli ellerinde olabilir?

0 Cevap