How can the PDO FetchMode FETCH_CLASS be utilized effectively in PHP to link data with objects?

To link data with objects using PDO FetchMode FETCH_CLASS in PHP, you can create a class that represents the structure of the data you want to fetch. By specifying the class name in the fetch mode, PDO will automatically instantiate objects of that class and populate their properties with the fetched data.

class User {
    public $id;
    public $username;
    public $email;
}

$stmt = $pdo->prepare("SELECT * FROM users");
$stmt->setFetchMode(PDO::FETCH_CLASS, 'User');
$stmt->execute();

$users = $stmt->fetchAll();

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