我正在编写一个类来处理内存缓存对象。这个想法是创建 abstract class Cachable
并且所有可缓存的对象(例如 User、Post 等)都将是该类的子类。
该类提供了一些方法,例如 Load()
,如果对象未被缓存,它会调用抽象函数 LoadFromDB()
,用于刷新/使缓存无效,等
主要问题在Load()
;我想做类似的事情:
protected function Load($id)
{
$this->memcacheId = $id;
$this->Connect();
$cached = $this->memcache->get(get_class($this) . ':' . $id);
if($cached === false)
{
$this->SetLoaded(LoadFromDB($id));
UpdateCache();
} else {
$this = $cached;
$this->SetLoaded(true);
}
}
不幸的是,我需要 $this
成为 $cached
(缓存对象);有什么办法吗? “每个可缓存对象都派生自可缓存类”是不是一个糟糕的设计理念?
最佳答案
将属性从 $cached 复制到 $this 怎么样?
foreach (get_object_vars($cached) as $field => $value) {
$this->$field = $value;
}
关于php - 有没有办法将对象反序列化为 "$this"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2952917/