Re: Singletons

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Colin Guthrie schrieb:
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

Hallo,
this is the Result of my test with your Code:

Fatal error: Access level to Singleton::__construct() must be public (as in class Base) in C:\Users\cmedina\Documents\test1.php on line 30

Regards

Carlos

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


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux