Re: Singletons



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
.



Relevant Pages

  • Re: Singletons
    ... A singleton would usually have a private constructor to prevent ... but you're then breaking one of the rules of the singleton pattern. ... public function __construct ...
    (php.general)
  • Re: [PHP] Singletons
    ... private static $thisObj = NULL; ... public function __construct ... You don't return it unless it already exists, not that it matters because this is the constructor and you can't return anything from that. ... The constructor has no involvement in management of the singleton instance so this is just all wrong. ...
    (php.general)
  • Re: Observer Design Pattern
    ... require 'singleton' ... singletons would have a static factory method ") to make themselves useful. ... how does the factory method decide which constructor to invoke? ... Will the include statement make the constructors become private if they were declared public? ...
    (comp.object)
  • Re: OOP database tables <-> php interface (semi LONG)
    ... where making the constructor private makes sense? ... public function __construct ... This is known as the "singleton" design pattern in the PHP ...
    (comp.lang.php)
  • Re: Singletons
    ... private static $thisObj = NULL; ... public static function singleton() ... public function setThisProp($sVal) ... Senior Web Developer ...
    (php.general)