你的问题和后续评论的措辞有些含糊不清,但他们仍然指出我的方向如下:
public function __construct($id) {
global $pdo, $memcached;
$data = $memcached->get($id);
if($memcached->getResultCode() == Memcached::RES_SUCCESS) {
// this is not currently allowed in PHP
$this = $data;
// this should be your fix
foreach($data AS $key => $value) {
$this->$key = $value;
}
// or this
foreach($this AS $key => $value) {
$this->$key = $data[$key];
}
// the difference between the fixes above is that
// the second is strictly limited to values defined
// by the class (current object)
}
else {
$pdos = $pdo->prepare('SELECT * FROM table_name WHERE id = ?');
if($pdos) {
// this is not allowed in PHP
$pdos->execute(array(intval($id)));
$this = $pdos->fetch(PDO::FETCH_CLASS, get_class($this));
// all of this should work fine and is allowed
$pdos->setFetchMode(PDO::FETCH_INTO, $this);
$pdos->execute(array(intval($id)));
$pdos->fetch(PDO::FETCH_INTO);
}
}
}但不幸的是,PHP不允许在内部覆盖$ this的值(在它自己的方法调用中),因此可以做的另一种方法是使用静态方法。
public static function getByID($id) {
global $pdo, $memcached;
$data = $memcached->get($id);
if($memcached->getResultCode() == Memcached::RES_SUCCESS) {
// this will work if your objects construct has a
// foreach similar to the ones presented above
$result = new self($data);
// or if you don't want to write a foreach in
// the construct you can have it here
foreach($data AS $key => $value) {
$this->$key = $value;
}
// or here
foreach($this AS $key => $value) {
$this->$key = $data[$key];
}
}
else {
$pdos = $pdo->prepare('SELECT * FROM table_name WHERE id = ?');
if($pdos) {
// either of these should work
$pdos->execute(array(intval($id)));
$result = $pdos->fetch(PDO::FETCH_CLASS, get_class($this));
// either of these should work
$result = new self;
$pdos->setFetchMode(PDO::FETCH_INTO, $result);
$pdos->execute(array(intval($id)));
$pdos->fetch(PDO::FETCH_INTO);
}
}
return($result);
}用法语法为MyClass::get($some_id)。