Re: Singletons
| From: | Colin Guthrie | Date: | Wed, 22 Oct 2008 09:13:49 +0000 |
| Subject: | Re: Singletons | ||
| References: | 1 2 3 4 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-282235@lists.php.net to get a copy of this message | ||
Stut wrote:
On 20 Oct 2008, at 20:24, Christoph Boget wrote: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) {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).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.public function __construct()A singleton would usually have a private constructor to prevent non-singleton instances.
$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/]