title: Creating a Singleton base class in PHP 5.3
body: <p>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 <strong>the</strong> 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:</p>
  
  <p>First, the super-class, providing singleton nature (requires PHP 5.3 or greater):</p>
  
  <pre><code>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;
      }
  
  }
  </code></pre>
  
  <p>Then we've got the the first singleton carrying a value:</p>
  
  <pre><code>require_once('Singleton.php');
  
  class SingletonA extends Singleton {
  
      protected $value;
  
      public function SingletonA() {
          $this-&gt;value = false;
      }
  
      public function getValue() {
          return $this-&gt;value;
      }
  
      public function setValue($value) {
          $this-&gt;value = $value;
      }
  
  }
  </code></pre>
  
  <p>Then the second singleton that references the first singleton:</p>
  
  <pre><code>require_once('Singleton.php');
  require_once('SingletonA.php');
  
  class SingletonB extends Singleton {
  
      public function getValue() {
          return SingletonA::getInstance()-&gt;getValue();
      }
  
  }
  </code></pre>
  
  <p>Now for the test that shows how this fails:</p>
  
  <pre><code>require_once('SingletonA.php');
  require_once('SingletonB.php');
  
  SingletonA::getInstance()-&gt;setValue(true);
  
  echo (SingletonA::getInstance()-&gt;getValue()) ? "true\n" : "false\n";
  echo (SingletonB::getInstance()-&gt;getValue()) ? "true\n" : "false\n";
  </code></pre>
  
  <p>The test yields the following output:</p>
  
  <pre><code>true
  false
  </code></pre>
  
  <p>Clearly, the SingletonA instance that the test code references is not the same instance that the SingletonB instance references. In short, SingletonA is not as single as I need it to be. How is this possible? And what magic can I wield to remedy this behaviour, giving me a true singleton?</p>