我有一点问题.这里是:
>这是我的单身抽象类:
abstract class Singleton { protected static $_instance = NULL; /** * Prevent direct object creation */ final private function __construct() { $this->actionBeforeInstantiate(); } /** * Prevent object cloning */ final private function __clone() { } /** * Returns new or existing Singleton instance * @return Singleton */ final public static function getInstance(){ if(null !== static::$_instance){ return static::$_instance; } static::$_instance = new static(); return static::$_instance; } abstract protected function actionBeforeInstantiate(); }
>之后我创建了一个抽象的注册表类:
abstract class BaseRegistry extends Singleton { //... }
>现在是会议注册的时候了.
class BaseSessionRegistry extends BaseRegistry { //... protected function actionBeforeInstantiate() { session_start(); } }
>最后一步:
class AppBaseSessionRegistryTwo extends BaseSessionRegistry { //... } class AppBaseSessionRegistry extends BaseSessionRegistry { //... }
>测试
$registry = AppBaseSessionRegistry::getInstance(); $registry2 =AppBaseSessionRegistryTwo::getInstance(); echo get_class($registry) . '|' . get_class($registry2) . '<br>';
输出:
AppBaseSessionRegistry|AppBaseSessionRegistry
我的期望是:
AppBaseSessionRegistry|AppBaseSessionRegistryTwo
为什么我得到这样的结果?
我怎样才能重新编写代码以获得我期望的结果?
更新:我在我的框架中使用它.用户将扩展我的BaseSessionRegistry类并添加他们的东西.我想在我的框架类中解决这个问题
你需要这样做:
class AppBaseSessionRegistryTwo extends BaseSessionRegistry { protected static $_instance = NULL; // ... } class AppBaseSessionRegistry extends BaseSessionRegistry { protected static $_instance = NULL; //... }
更新:
如果您不希望子类声明静态属性,则可以将静态属性声明为父类的数组.
abstract class Singleton { protected static $_instances = array(); // ... /** * Returns new or existing Singleton instance * @return Singleton */ final public static function getInstance(){ $class_name = get_called_class(); if(isset(self::$_instances[$class_name])){ return self::$_instances[$class_name]; } return self::$_instances[$class_name] = new static(); } abstract protected function actionBeforeInstantiate(); }