PDOStatement
在线手册:中文  英文

PDOStatement::fetchObject

(PHP 5 >= 5.1.0, PECL pdo >= 0.2.4)

PDOStatement::fetchObject获取下一行并作为一个对象返回。

说明

mixed PDOStatement::fetchObject ([ string $class_name = "stdClass" [, array $ctor_args ]] )

获取下一行并作为一个对象返回。此函数(方法)是使用 PDO::FETCH_CLASSPDO::FETCH_OBJ 风格的 PDOStatement::fetch() 的一种替代。

参数

class_name

创建类的名称。

ctor_args

此数组的元素被传递给构造函数。

返回值

返回一个属性名对应于列名的所要求类的实例, 或者在失败时返回 FALSE.

参见


PDOStatement
在线手册:中文  英文

用户评论:

rasmus at mindplay dot dk (2013-03-23 21:53:56)

Be warned of the rather unorthodox behavior of PDOStatement::fetchObject() which injects property-values BEFORE invoking the constructor - in other words, if your class initializes property-values to defaults in the constructor, you will be overwriting the values injected by fetchObject() !
A var_dump($this) in your __construct() method will reveal that property-values have been initialized prior to calling your constructor, so be careful.
For this reason, I strongly recommend hydrating your objects manually, after retrieving the data as an array, rather than trying to have PDO apply properties directly to your objects.
Clearly somebody thought they were being clever here - allowing you to access hydrated property-values from the constructor. Unfortunately, this is just not how OOP works - the constructor, by definition, is the first method called upon construction.
If you need to initialize your objects after they have been constructed and hydrated, I suggest your model types implement an interface with an init() method, and you data access layer invoke this method (if implemented) after hydrating.

易百教程