How can errors be effectively debugged when using PDO in a PHP class?

When debugging errors in PDO within a PHP class, it is important to enable error reporting and exception handling to catch any issues that may arise. By setting PDO to throw exceptions, any errors can be caught and handled appropriately, providing more detailed information on what went wrong. Additionally, utilizing try-catch blocks can help isolate and handle specific errors within the class.

<?php
class Database {
    private $host = 'localhost';
    private $username = 'root';
    private $password = '';
    private $dbname = 'mydatabase';
    private $conn;

    public function __construct() {
        $dsn = "mysql:host=$this->host;dbname=$this->dbname";
        $options = array(
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        );

        try {
            $this->conn = new PDO($dsn, $this->username, $this->password, $options);
        } catch(PDOException $e) {
            echo "Connection failed: " . $e->getMessage();
        }
    }
}
?>