I have a PHP class (POJO_FOO
) which maps to a table (TABLE_FOO
).
e.g. one row equal to one object of that class.
Now I am writing a manager which returns array of such objects matching a particular query. Using PDO
, how can I return array of objects ?
When I do simple fetchAll
, it returns array (representing number of results) of associative array (column
=> value
). Is there a option in fetchALL
which can give me result in form of array of objects ?
-
wow it works ... don't know why it wasn't working when I tried. anyways .. thanks for the answer.mrd081– mrd0812012年08月28日 08:32:51 +00:00Commented Aug 28, 2012 at 8:32
1 Answer 1
you can use PDO::FETCH_CLASS to hydrate your class with your data :
return $pdo->query('SELECT * FROM tablefoo')->fetchAll(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE,'POJO_FOO');
it is also useful to use PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE because it makes the construction of the object more consistent. Habitualy your constructor is called before everything. If you do not use FETCH_PROPS_LATE it will called after your properties are hydrated.