抽象单例模式类

时间:2012-01-21 15:47:00

标签: php oop singleton

我正在努力实现以下目标:

使用这个通用单例类:

abstract class Singleton {

    private static $instance = null;

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

      return self::$instance;
    }
}

我希望能够创建Singleton具体类,例如:

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

然后将它们用作:

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

但遗憾的是__CLASS__意图为Singleton,因此PHP无法实例化抽象类时会发生致命错误。但事实是我希望实例化Registry(例如)。

所以我尝试使用get_class($this)但是作为一个静态类,Singleton没有$ this。

我该怎么做才能让它发挥作用?

1 个答案:

答案 0 :(得分:5)

幻灯片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()
    {}
}

然后你可以做

class A extends Singleton
{
    protected static $instance;
}

如果您需要在扩展类中执行其他设置逻辑覆盖init

另见Is there a use-case for singletons with database access in PHP?