I wonder when do I have to use PDO::FETCH_CLASS and what is the benefit of using it rather than using other fetch method like PDO::FETCH_ASSOC?
-
1What is your other fetch method? – ʰᵈˑ Feb 11 '15 at 17:06
-
Oh, you mean you want to know the difference and benefits of using either `PDOStatement::fetch(PDO::FETCH_ASSOC)` or `PDOStatement::fetch(PDO::FETCH_OBJ)`? – ʰᵈˑ Feb 11 '15 at 17:08
-
yes. comparing with PDO::FETCH_CLASS – Eko Feb 11 '15 at 17:10
-
well , my comment is stupid ; but it's all explain here : http://php.net/manual/fr/pdostatement.fetch.php – ssbb Feb 11 '15 at 17:14
-
i know about that, but i still didn't get it, when do i should use FETCH_CLASS meanwhile i can do it by using FETCH_ASSOC – Eko Feb 11 '15 at 17:16
-
1FETCH_CLASS return a new instance => you can call some function. FETCH_ASSOC return an array => you can print some result. Many case you will want an instance instead of an array of value – ssbb Feb 11 '15 at 17:19
-
can you tell me in what case or example? that's my point, i need to know in what case :D – Eko Feb 11 '15 at 17:23
1 Answers
It depends on what you like or need.
PDO::FETCH_ASSOC
makes fetch return an associative array.
PDO::FETCH_OBJ
is similar, but return an 'anonymous object' with properties. Note that actually 'anonymous object' is the wrong term, but the PHP documentation also uses it. It refers to an object that inherites from StdClass.
PDO::FETCH_CLASS
is a variation to that. It doesn't use StdClass, but creates an object of a specific (given) class type and tries to map column values to properties of that object.
This is useful if you don't want to use StdClass, but want to use a 'smart' object instead. For instance if you have a User table with FirstName and LastName, you could let PDO::fetch return a User
object that implements a getFullName
method that returns the concatenated first and last name. StdClass won't have this method, and neither will your array.
But still, if you like working with arrays, there is no need for you to switch to any of the other two. Use what you like best.
-
so if for some case i need some information from article table, it is better to use assoc rather than extract it into a class? – Eko Feb 11 '15 at 17:25
-
It's not better or worse. It's just a matter of opinion. You can use either. – GolezTrol Feb 11 '15 at 17:26
-
-
1If you wanted to use ORM to access your data, you'd use `PDO::FETCH_CLASS`, for example. – ʰᵈˑ Feb 11 '15 at 17:27
-