【发布时间】:2012-02-26 14:34:26
【问题描述】:
我有一个名为Admin 的类,它的字段与我在数据库中的admins 表中的字段完全相同:id、email、pwhash、pwnonce、@ 987654327@,permissions.
我的班级看起来像这样(简化了):
class Admin {
var $id, $email, $pwhash, $pwnonce, $name, $permissions;
function auth() {
// checks the session and attempts to authenticate the user
}
function login($email,$pw) {
// authenticate the user and start a session for them.
}
}
问题是,我想用 PDO 来获取一个使用当前类的对象,并将它分配给当前对象。
以前,我获取一个 assoc 数组并一一分配所有变量,但现在,由于我正在更改我的系统以使用 PDO,我想让它返回一个 Admin 的实例类,我分配给当前类。
例如,在auth()方法中,应该是这样的:
function auth() {
if (!isset($_SESSION['id'])) return false;
$id = $_SESSION['id'];
// create PDO connection and assign to $dbh
$sth = $dbh->prepare('SELECT * FROM admins WHERE id = ?');
$sth->execute(array($id));
$sth->setFetchMode(PDO::FETCH_CLASS,get_class($this));
$obj = $sth->fetch();
if (!is_object($obj)) return false;
$this = $obj; // I know this won't work, but anyway...
}
所以我尝试了,正如我所怀疑的那样,它不会让我分配 $this 的值。但是我还是想使用PDO的对象映射功能,那么如何将PDO返回的对象分配给我所在的实例呢?
【问题讨论】:
-
什么是
$this->getClass(),它返回什么?它应该将类的名称作为字符串返回。 -
@FrancisAvila 呜呜——我的意思是
get_class($this)