Skip to content
Advertisement

PHP PDO to create an object of a class with fetchObject

I am trying to create a “User” object inside my class “User” based on the properties I have stored inside my database, which I use PDO to connect to.

I’ve search some pages on Google and found that most people use the fetchObject method for that. Right now, I am trying to use this to create an object of this current class but I keep getting the error:

Fatal error: Uncaught ArgumentCountError: Too few arguments to function User::__construct(), 0 passed and exactly 11 expected in …

Everyone keeps using this one the web but I can’t seem to find their constructors, because they may not have any attributes to receive.

My current code is this:

public static function createUserBySQL($id)
    {
        $stmt = BD::getConnection()->prepare("SELECT * FROM user WHERE username = ?");
        $stmt->execute([$id]);
        $user = $stmt->fetchObject(__CLASS__);
        var_dump($user);
        return $user;
    }

This may be easy to solve but it’s my first time doing OOP in PHP with PDO, so I don’t know yet all of the tips and tricks to workaround that easily 😉

Thanks,
mikeysantana

QUICK EDIT: All of the attributes from “User” instance are private and I wanted to keep it like that to maintain the code logic.

Advertisement

Answer

You need to make the parameters to your constructor optional. The documentation says:

When an object is fetched, its properties are assigned from respective column values, and afterwards its constructor is invoked.

When the constructor is invoked, no arguments are supplied, which is why you’re getting that error.

The constructor needs to check whether the arguments were explicitly provided, and only fill in the properties when they are. There are some examples of how to do this in the comments section of the above documentation.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement