php – 后期静态绑定
发布时间:2020-12-13 18:00:37 所属栏目:PHP教程 来源:网络整理
导读:我有一点问题.这里是: 这是我的单身抽象类: abstract class Singleton {protected static $_instance = NULL;/** * Prevent direct object creation */final private function __construct(){ $this-actionBeforeInstantiate();}/** * Prevent object clon
我有一点问题.这里是:
>这是我的单身抽象类: 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(); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |