我正在努力实现以下目标:
使用这个一般的单例类:
abstract class Singleton {
private static $instance = null;
public static function self()
{
if(self::$instance == null)
{
$c = __CLASS__;
self::$instance = new $c;
}
return self::$instance;
}
}
Run Code Online (Sandbox Code Playgroud)
我很想能够创建Singleton具体类,例如:
class Registry extends Singleton {
private function __construct() {}
...
}
Run Code Online (Sandbox Code Playgroud)
然后将它们用作:
Registry::self()->myAwesomePonyRelatedMethod();
Run Code Online (Sandbox Code Playgroud)
但遗憾的__CLASS__
是,因为Singleton
PHP无法实例化抽象类而导致致命错误.但事实是我希望实例化Registry(例如).
所以我试过get_class($this)
但是作为一个静态类,Singleton没有$ this.
我能做些什么才能让它发挥作用?
来自我的Slides Singletons的简单代码 - 为什么它们很糟糕以及如何从应用程序中消除它们:
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()
{}
}
Run Code Online (Sandbox Code Playgroud)
那你可以做
class A extends Singleton
{
protected static $instance;
}
Run Code Online (Sandbox Code Playgroud)
如果需要init
在扩展类中执行其他设置逻辑覆盖.
归档时间: |
|
查看次数: |
500 次 |
最近记录: |