When using FETCH_CLASS with PDO in PHP to fetch objects from a database query, how are the properties of the object populated and accessed?

When using FETCH_CLASS with PDO in PHP to fetch objects from a database query, the properties of the object are automatically populated with the values retrieved from the database columns. To access these properties, you can simply use object notation ($object->property_name) to retrieve the values.

// Example code snippet
class User {
    public $id;
    public $username;
    public $email;
}

$pdo = new PDO('mysql:host=localhost;dbname=test_db', 'username', 'password');
$stmt = $pdo->query("SELECT * FROM users");
$stmt->setFetchMode(PDO::FETCH_CLASS, 'User');
$users = $stmt->fetchAll();

foreach ($users as $user) {
    echo $user->id . ' - ' . $user->username . ' - ' . $user->email . '<br>';
}