note 53483 deleted from language.oop5.patterns by danbrown

From: Date: Sun, 23 Jan 2011 16:48:04 +0000
Subject: note 53483 deleted from language.oop5.patterns by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-176123@lists.php.net to get a copy of this message
Note Submitter: traxer ad gmx.net ---- In response to Richard Quadling's response to Scott Mattock's response to Jimmy Paterson ... The singleton pattern is a /pattern/, not a class. There is no way to move the whole functionality of 'being a singleton' into a common base class, it was not intended that way. There is no point in adding features to derived classes, other than for internal use, either. Furthermore, when I derive two classes from Singleton, the singleton is not really a singleton anymore. Considering this, I think your implementation of Singleton and SubClass (i.e your correction to Scott Mattock's) is the one that most closely matches the intention of GOF. You can allow sublasses of SubClass, though: <?php class Singleton { private static $instance; public static function singleton($class = __CLASS__) { if (!isset(self::$instance)) self::$instance = new $classname; return self::$instance; } } class SubClass extends Singleton { public static function singleton($class = __CLASS__) { return parent::singleton($class); } } class SubSubClass extends SubClass { public static function singleton($class = __CLASS__) { return parent::singleton($class); } } ?> This even works with php4 if you 1. move the Singleton::$instance into function Singleton::singleton, 2. get rid of the unsuported keywords and 3. rename the Singleton::singleton method (so as not to be a constructor). So no real imporvement here, except for the added protection of not beeing able to create objects explicitly.

« previous php.notes (#176123) next »