将 PDO 结果集转换为对象数组

sup*_*own 2 php pdo crud object

我有一个名为 Product 的 PHP 类:

class Product {

   $id;
   $name;

}
Run Code Online (Sandbox Code Playgroud)

另一个从数据库获取数据的类:

$stm = $this->dsn->prepare($sql);

$stm->execute();

$rst = $stm->fetchAll(PDO::FETCH_ASSOC);
Run Code Online (Sandbox Code Playgroud)

如何将此 PDO 结果集 ($rst) 转换为 Product 对象数组?

Dan*_*jel 5

使用PDO::FETCH_CLASS论证。

class Product {
    public $id;
    public $name;
}

$stm = $this->dsn->prepare($sql);
$stm->execute();

$result = $stm->fetchAll( PDO::FETCH_CLASS, "Product" );
Run Code Online (Sandbox Code Playgroud)

http://php.net/manual/en/pdostatement.fetchall.php