What is the purpose of using PDO::FETCH_CLASS in PHP and how does it differ from other fetch modes?

When using PDO to fetch data from a database in PHP, the fetch mode determines how the data is returned. PDO::FETCH_CLASS is used to fetch data into a new instance of a specified class, mapping the columns of the result set to properties of the class. This differs from other fetch modes like PDO::FETCH_ASSOC or PDO::FETCH_OBJ, which return data as associative arrays or objects respectively.

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

$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
$stmt = $pdo->query('SELECT id, username, email FROM users');
$stmt->setFetchMode(PDO::FETCH_CLASS, 'User');
$user = $stmt->fetch();

echo $user->id;
echo $user->username;
echo $user->email;