7

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 ?

tereško
58.5k26 gold badges100 silver badges151 bronze badges
asked Aug 28, 2012 at 8:17
1
  • wow it works ... don't know why it wasn't working when I tried. anyways .. thanks for the answer. Commented Aug 28, 2012 at 8:32

1 Answer 1

8

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.

answered Aug 28, 2012 at 8:21
Sign up to request clarification or add additional context in comments.

4 Comments

wow it works ... don't know why it wasn't working when I tried. anyways .. thanks for the answer :)
a litle comment about PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE
what will that do ? (FETCH_PROPS_LATE)
I tried to explain it : -without PROPS_LATE : PDO hydrates your object and then calls the constructor. If your constructor does call a important initialisation process, it is bad -with PROPS_LATE : PDO calls your constructor and then hydrate your object : that's consistent and secured.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.