facumontero facumontero - 3 months ago 15x
PHP Question

PDO class extends and fetch class in PHP

Sorry, the question was too bad to have a proper answer, so now I edited:

The manual says:

PDO::FETCH_CLASS: Returns instances of the specified class, mapping the columns of each row to named properties in the class.

My doubt is if the class extends form another class that have more atributes, will be this atributes instantiated?

Sorry if I'm not clear with the question, I'm not English speaker. Thank you all.


A good question.

For PDO, a class hierarchy doesn't actually matter. What PDO is doing is simply taking columns from database and assigning them to class properties, regardless of the class definition or inheritance.

  • If a property doesn't exist, PDO will try to create it.
  • If there is a property for which there is no column to map - then PDO will leave it alone.

As simple as that. So, it should create anything you select from the database.

As of the particular code you had in your question before - you have to debug it. Look, to see if anything was fetched, you are using whatever method printNickName(). But there could be any error either with this method or any intermediate process. Let me suggest you to create just empty classes, fetch your data in them, and check the properties directly.

After you make sure that all the properties are properly set, you may try with your custom class definitions. To debug the returned data I'd suggest to use

var_dump($stmt->fetchAll(PDO::FETCH_CLASS, 'User'));

You may learn other details of PDO class handling from my article, Fetching objects with PDO