1

I'm trying to achieve the following goal:

Using this general singleton class:

abstract class Singleton {

    private static $instance = null;

    public static function self()
    {
      if(self::$instance == null)
      {   
         $c = __CLASS__;
         self::$instance = new $c;
      }

      return self::$instance;
    }
}

I'd love to be able to create Singleton concrete class such as:

class Registry extends Singleton {
    private function __construct() {}
    ...
}

and then use them as:

Registry::self()->myAwesomePonyRelatedMethod();

But obliviously __CLASS__ is intended as Singleton so a fatal error occurs about PHP not being able to instantiate an abstract class. But the truth is that I want Registry (for example) to be instantiated.

So I tried with get_class($this) but being a static class, Singleton has no $this.

What could I do to make it work?

Shoe
  • 70,092
  • 30
  • 150
  • 251

1 Answers1

5

Abridged code from my Slides Singletons in PHP - Why they are bad and how you can eliminate them from your applications:

abstract class Singleton
{
    public static function getInstance()
    {
        return isset(static::$instance)
            ? static::$instance
            : static::$instance = new static();
    }

    final private function __construct()
    {
        static::init();
    }

    final public function __clone() {
        throw new Exception('Not Allowed');
    }

    final public function __wakeup() {
        throw new Exception('Not Allowed');
    }

    protected function init()
    {}
}

Then you can do

class A extends Singleton
{
    protected static $instance;
}

If you need to do additional setup logic override init in the extending class.

Also see Is there a use-case for singletons with database access in PHP?

Community
  • 1
  • 1
Gordon
  • 296,205
  • 68
  • 508
  • 534
  • 2
    @Gordon, you have just destroyed my project idea. How cruel! I loved Singleton before, and now I read all this bad things about them :(. So basically to avoid them I should use dependency injection pattern? – Shoe Jan 21 '12 at 16:08
  • 1
    @JeffPigarelli I'd say sorry if I wouldn't consider this a major WIN ;) Yes. Dependency Injection is the way to go. And separation of creator graphs and collaborator graphs. See http://misko.hevery.com/2008/08/21/where-have-all-the-singletons-gone/ – Gordon Jan 21 '12 at 16:09