我试图从数据库中获取所有记录,然后用每个记录的数据实例化一个新的对象。
$stmt = $this->pdo->prepare('SELECT * FROM '.$this->table.' ORDER BY '.$order.' ASC');
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ($results){
for ($i=0; $i<count($results); ++$i){
$strValues = '';
$values = array_values($results[$i]);
for ($j=0; $j<count($values); ++$j){//Extract the values to pass them as arguments to the constructor below
if ($j == 0) $strValues .= $values[$j];
else{
$strValues .= ',';
$strValues .= '"'.$values[$j].'"';
}
}
eval('$result['.$i.'] = new '.get_class($this->instance).'('.$strValues.');');
}
}
问题是对象的类型可能会有所不同,这取决于我是否在查询这些记录。用户 或 标签 数据库,所以对构造函数的调用可能是 new User(user_id, username, name, surname) 或 new Label(label_id, name, description, color). 上面的代码运行在 ObjectMapper 类,它在创建时被分配了一个对象类型,并将其实例存储在私有的 实例 变量。 这样,我就可以通过使用 get_class($this->instance).
我终于设法使它工作,使用一个 评价 如图所示,但我读到这不是一个好的做法,我想知道有什么更好更干净的方法。
这应该可以达到你想要达到的目的。不要使用 eval
PDO有很多有用的取款模式,这里介绍一下。https:/phpdelusions.netpdofetch_modes#FETCH_CLASS。
$stmt = $this->pdo->prepare('SELECT * FROM '.$this->table.' ORDER BY '.$order.' ASC');
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_CLASS, get_class($this->instance));
P.S.记得正确地将表名和白名单化。$order
可变的。