I’ve got a class called Admin, and it has exactly the same fields as those in my admins table in the database: id, email, pwhash, pwnonce, name, permissions.
My class looks like this (simplified down):
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.
}
}
The problem is, I want to use PDO to fetch an object using the current class, and assign it to the current object.
Before, I was fetching an assoc array and assigning all the variables one-by-one, but now, since I’m changing my system to use PDO, I want to get it to return an instance of the Admin class, which I assign to the current one.
For example, in the auth() method, it should be something like this:
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...
}
So I tried that, and as I had suspected, it won’t let me assign the value of $this. However, I still want to use the object mapping functionality of PDO, so how can I assign the object returned from PDO to the instance I’m in?
Rather then trying to override
$this, return the object in question:Then use it like so:
Which would override the current admin object.
Though a better approach would be to assign the variables to the current object, or to use an abstraction class, it would make more sense.
Try to say what you’re doing out loud. You’re telling an
Admintoauth(), and then replace itself with a newAdminthat’s authenticated. Rather, you should have anAdminManagerprocess the authentication request, and return anAdminobject, or, have theAdminitself authenticate, and then fill in the details in that same object.Other than making sense, you’re also preventing duplicates and memory leaks in your application.