Re: Reusable Singleton pattern using PHP5
| From: | Jochem Maas | Date: | Mon, 24 Apr 2006 22:55:37 +0000 |
| Subject: | Re: Reusable Singleton pattern using PHP5 | ||
| References: | 1 2 3 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-234644@lists.php.net to get a copy of this message | ||
Simas Toleikis wrote:
not sure namespaces will make it ... I believe the decision on that is still out.php6 will include static late bindingGreat. Love the other new features, especially namespaces.
my bad - I was thinking out loud and didn't check. here is a less elegant hack that does get some of the way to where you want to be (take a look at what happens if you set Singleton::__construct() as private - you get a weird error, which to me smell like a bug - but then again there is some logic to it, although I wonder if it's intended) : <?php class Test extends Singleton {- until then you have 2 choices, create a hack (see below) or stick redundant code into each class you want to be a singleton.The hack doesn't work (See below). Guess we are left with copy-paste
static public function getInstance()
{
return self::_getInstance(__CLASS__);
}
}
abstract class Singleton
{
private static $instance;
protected function __construct() {}
private function __clone() {}
abstract static public function getInstance();
protected static function _getInstance($c)
{
if (!isset(self::$instance)) {
self::$instance = new $c;
}
return self::$instance;
}
}
var_dump( Test::getInstance() );
?>
thing :-/ Though i wonder if there are any other hacks using some sort of classkit/other class manipulation functions?probably runkit (or is it classkit - can't remember which of those is more actively developed) might give a way out - but I would recommend it for production code.
yeah - put it down to a thinko.public static function GetInstance() {Isn't that self::$class the same "late static binding" thing? :-) As iif (!isset(self::$instance)) { if (!isset(self::$class)) {
get it, at this point from Singleton::GetInstance() you can't get the static $class member of Test class.