php – 后期静态绑定

我有一点问题.这里是:

>这是我的单身抽象类:

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();

}

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...