【问题标题】:Separate static variable for every child为每个孩子单独的静态变量
【发布时间】:2011-08-20 08:39:07
【问题描述】:

我想在我的 ORM 中做一些缓存

class Base {

    static public $v=array();
    static public function createById($id){
        if(!array_key_exists($id, static::$v)){
            static::$v[$id] = new static; //Get from DB here. new static is just example
        }
        return static::$v[$id];
    }

}

class User extends Base{

}
class Entity extends Base{

}

但是现在缓存被合并了

var_dump(User::createById(1));
var_dump(Entity::createById(1));

结果

object(Model\User)#4 (0) {
}
object(model\User)#4 (0) {
}

如果我做了

class Entity extends Base{
    static public $v=array();
}
class User extends Base{
    static public $v=array();
}

我得到了我需要的东西:

object(Model\User)#4 (0) {
}
object(model\Entity)#5 (0) {
}

是否可以在每个类中不声明的情况下做到这一点?

【问题讨论】:

    标签: php oop caching orm


    【解决方案1】:

    如果您不在每个子类中重新声明属性非常重要,那么我能想到的唯一解决方案是,这不是您想要的,但它应该为您提供相同的功能,是在基类上共享相同的属性来存储所有子类的缓存,但使用子类名作为缓存数组中的键:

    class Base {
       public static $v=array();
       public static function createById($id){
            $called = get_called_class();
            if (!isset(self::$v[$called])) {
                self::$v[$called] = array();
            }
            $class_cache = &self::$v[$called];
            if(!array_key_exists($id, $class_cache)){
                $class_cache[$id] = new static;
            }
            return $class_cache[$id];
        }
    }
    

    是的,它不漂亮......但是 AFAIK,你要求的东西是不可能的。

    【讨论】:

    • 反正比在每一个子类里redeclare都漂亮:) 1 写一次,不用多想,谢谢。
    猜你喜欢
    • 2020-11-09
    • 1970-01-01
    • 2013-07-12
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-29
    相关资源
    最近更新 更多