What are the best practices for initializing class properties in PHP, especially when fetching data from a database?

When initializing class properties in PHP, especially when fetching data from a database, it is best practice to use a constructor method to set the initial values of the properties. This ensures that the object is properly initialized when it is created and reduces the risk of uninitialized properties causing errors later on. Additionally, using prepared statements when fetching data from a database helps prevent SQL injection attacks.

class User {
    private $id;
    private $username;
    private $email;

    public function __construct($id) {
        $this->id = $id;

        // Fetch user data from database
        $stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
        $stmt->execute(['id' => $id]);
        $user = $stmt->fetch();

        $this->username = $user['username'];
        $this->email = $user['email'];
    }
}