Stut wrote:
On 20 Oct 2008, at 20:24, Christoph Boget wrote:
 public function __construct()
A singleton would usually have a private constructor to prevent
non-singleton instances.

The problem being if the class in question derives from another class
that has a public constructor...  If you are in that particular
situation (which I am), you're basically SOL and the statement above
has no bearing.

Correct, but you're then breaking one of the rules of the singleton pattern. If you're stuck with that then you'll need to enforce the singleton aspect in non-technical ways (policy, regular beatings, etc).


I disagree (not with the regular beatings... that's very important for moral!), but with the statement that says you are SOL if you want to create a singleton that derives from another class with a public constructor, you just have to make the derived class' constructor private and call the parent's constructor:


class Base
{
  private $foo;
  public function __construct($foo)
  {
    $this->foo = $foo;
  }

  public function getFoo()
  {
    return $this->foo;
  }
}

class Singleton extends Base
{
  private function __construct()
  {
    parent::__construct("Singleton");
  }

  public static function getInstance()
  {
    static $instance = null;
    if (!isset($instance))
      $instance = new self();
    return $instance;
  }
}


$bar = Singleton::getInstance();
$bar->getFoo(); // "Singleton"


(entirely untested)

Col

--

Colin Guthrie
gmane(at)colin.guthr.ie
http://colin.guthr.ie/

Day Job:
  Tribalogic Limited [http://www.tribalogic.net/]
Open Source:
  Mandriva Linux Contributor [http://www.mandriva.com/]
  PulseAudio Hacker [http://www.pulseaudio.org/]
  Trac Hacker [http://trac.edgewall.org/]


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to