微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐