Re: Singletons
| From: | Carlos Medina | Date: | Wed, 22 Oct 2008 09:27:30 +0000 |
| Subject: | Re: Singletons | ||
| References: | 1 2 3 4 5 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-282237@lists.php.net to get a copy of this message | ||
Colin Guthrie schrieb:
Stut wrote: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 CarlosOn 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 Hallo,