donglan9651 2012-01-21 15:47
浏览 65
已采纳

抽象单例模式类

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?

  • 写回答

1条回答 默认 最新

  • douyun1972 2012-01-21 15:55
    关注

    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?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?