Search code examples
phpclassooppdo

Need to Fetch the data in PDO::FETCH_CLASS in PHP


I am facing a little problem, I have a User class that connects to the database using a static::method and fetching all users using my custom method find_all(), the result is gonna be returned associative array or objects, I need the data to be objects associated to my class, so I have to use fetchAll(PDO::FETCH_CLASS, 'Users'), the problem is, i want to use my class which it is using a __construct() method to build objects, it gives me properties are required, I shouldn't use default values in this case, cuze I want the result from the database instead, I hope you got that, thanks in advance.

I tried to use default values, buy aren't working with this situation


Solution

  • Try this PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE

    This will allows the properties to be set before the constructor is called, enabling you to initialize your object properly without running into issues with missing required properties.