Re: Reusable Singleton pattern using PHP5

From: 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:
php6 will include static late binding
Great. Love the other new features, especially namespaces.
not sure namespaces will make it ... I believe the decision on that is still out.
- 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
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 {
    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.
public static function GetInstance() {
       if (!isset(self::$instance)) {
               if (!isset(self::$class)) {
Isn't that self::$class the same "late static binding" thing? :-) As i
yeah - put it down to a thinko.
get it, at this point from Singleton::GetInstance() you can't get the static $class member of Test class.


« previous php.general (#234644) next »