Re: Reusable Singleton pattern using PHP5

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



[top posting to just to spite the anti-top-posting crowd :-P]

php6 will include static late binding - until then you have 2 choices,
create a hack (see below) or stick redundant code into each class you
want to be a singleton.

(welcome to the club that thinks this should have been possible
right from the beginning - I'm a member since 2003 - it doesn't get any
less annoying ;-)

one way to hack it:

class Test extends Singleton
{	
	protected static $class = self; // if self doesn't work use 'Test'
}

abstract class Singleton
{
   private   static $instance;
   protected static $class;

   private function __construct() {}
   private function __clone() {}

   public static function GetInstance()
   {
     	if (!isset(self::$instance)) {
		if (!isset(self::$class)) {
			throw new Exception('ya need to define self::$class in your subclass');
		}

        	self::$instance = new self::$class;
 	}
     	return self::$instance;
   }
}

ps - search the web for 'late static binding + php' and the like and
you'll [hopefully] find plenty in the internals mailing list archives
about this (for instance)

Simas Toleikis wrote:
Hello,

As the %subj% says.. can't get it to work with PHP5. I mean, you could
do this kind of stuff with templates/generics on other languages and
then make a class singleton by just inheriting from base Singleton
class. No need to redefine GetInstance() (which usually contains the
same redundant kind of code). It should look something like this in
PHP5:

class Test extends Singleton
{
  // no singleton-specific code here
}

abstract class Singleton
{
  private static $instance = null;
  private function __construct() {}
  private function __clone() {}
  public static function GetInstance()
  {
    if (!isset(self::$instance))
      self::$instance = new self; // <-- doesnt really work

    return self::$instance;
  }
}

The problem is that self refers to Singleton class. I have also been
playing with __CLASS__ magic constant but it does the same thing.
Someone got it working the right way?

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux