从父类设置模型


Set model from parent class

我有这个类,我尝试从类查询设置用户变量。我怎么能做到呢?因此,在执行$user = new User(1)之后,$user变量将拥有id = 1的用户的所有信息。

class User extends UserQueries{
    private $username = null,
            $password = null,
            $date_registered = null;
    public function __construct($id){
        $this->table = "users";
        parent::__construct($id);
    }
    ...
}
class UserQueries extends Queries{
    protected function __construct($id) {
        parent::__construct($id);
    }
    ...
}
class Queries extends Model{
    protected $table = NULL, $isLoaded = FALSE;
    protected function __construct($id, $debug = FALSE) {
        parent::__construct();
        if(is_null($id)){
            $this->isLoaded = FALSE;
        }
        else{
            if(is_null($this->table)){
                $this->isLoaded = FALSE;
            }
            else{
                $this->set_object($id);
            }
        }
    }
    private function set_object($id){
        $sql = "SELECT * FROM :table WHERE id = :id";
        $query = $this->database->prepare($sql);
        $query->execute(array(':table' => $this->table, ':id' => $id));
        $this->isLoaded = $query->rowCount();
        if ($this->isLoaded) {
            //Here I want to set User variables using fetchObject
        }
    }
}

我认为您想使用PDO::FETCH_INTO标志的获取方法。它将尝试将从数据库中获取的数据加载到现有对象中。

$query->setFetchMode(PDO::FETCH_INTO, $this);
$query->execute();
$query->fetch();

我相信PDO不可能访问私有成员,所以你可能需要添加一个魔术setter来处理这个问题。