Reputation: 279
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 ?
Upvotes: 7
Views: 2853
Reputation: 3713
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.
Upvotes: 8