skip to Main Content

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

2

Answers


  1. Chosen as BEST ANSWER
    public function __construct($name = null, $email = null, $phone = null, $country = null, $password = null) {
        $this->name = $name;
        $this->email = $email;
        $this->phone = $phone;
        $this->country = $country;
        $this->password = $password;
    }
    
    public static function find_all() {
        $stmt = static::connect_database()->query('SELECT * FROM users');
        $stmt->setFetchMode(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, 'User');
        return $stmt->fetchAll();
    }
    

    Works fine, thanks to @M.hammad_Nazir & @Muhammad_Arsal


  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search