我有一个PHP类Product:
class Product {
$id;
$name;
}
和另一个从数据库获取数据的类:
$stm = $this->dsn->prepare($sql);
$stm->execute();
$rst = $stm->fetchAll(PDO::FETCH_ASSOC);
我如何将这个PDO结果集($rst)转换为对象Product的数组?
使用PDO::FETCH_CLASS
参数
class Product {
public $id;
public $name;
}
$stm = $this->dsn->prepare($sql);
$stm->execute();
$result = $stm->fetchAll( PDO::FETCH_CLASS, "Product" );
http://php.net/manual/en/pdostatement.fetchall.php 只要改变你调用fetchAll()的方式
$rst = $stm->fetchAll(PDO::FETCH_CLASS, 'Product');
在这种情况下,我的方法是在Product类中使用一个辅助函数,该函数构建对象的新实例,并在提供PDO的输入时返回它。
等public static function buildFromPDO($data) {
$product = new Product();
$product->id = $data["id"];
$product->name = $data["name"];
return $product;
}
然后在你的PDO调用中,通过return和array_push
循环到一个包含通过该函数构建的所有产品的数组。
$products = array();
foreach ($rst as $r) {
array_push($products, Product::buildFromPDO($r));
}
如果你要做很多这样的事情,你也可以考虑使用ORM
你必须写一个方法来做。
class Product {
$id;
$name;
public function loadData($data){
$this->id = $data['id'];
$this->name = $data['name'];
}
}
$Product = new Product();
$Product->loadData($database_results);
或者,如果你要对每个对象都这样做,使用构造函数。
class Product {
$id;
$name;
public function __construct($id, $pdo){
$pdo->prepare("select * from table where id = :id");
// do your query, then...
$this->id = $data['id'];
$this->name = $data['name'];
}
}
$Product = new Product($id, $pdo);
可以使用构造函数参数(http://php.net/manual/en/pdostatement.fetchall.php)
$result = $stm->fetchAll( PDO::FETCH_CLASS, "Product", array('id','name'));
注意:属性必须是公共的