Are there any specific parameters or considerations to keep in mind when using PDO connections in PHP classes?

When using PDO connections in PHP classes, it is important to ensure that the connection is properly handled and maintained throughout the class. This includes establishing the connection in the class constructor and closing it in the destructor to prevent resource leaks. Additionally, error handling should be implemented to catch any exceptions that may occur during database operations.

class DatabaseConnection {
    private $pdo;

    public function __construct($dsn, $username, $password) {
        try {
            $this->pdo = new PDO($dsn, $username, $password);
            $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (PDOException $e) {
            echo "Connection failed: " . $e->getMessage();
        }
    }

    public function query($sql) {
        try {
            $stmt = $this->pdo->query($sql);
            return $stmt->fetchAll();
        } catch (PDOException $e) {
            echo "Query failed: " . $e->getMessage();
        }
    }

    public function __destruct() {
        $this->pdo = null;
    }
}

// Example of using the DatabaseConnection class
$dsn = "mysql:host=localhost;dbname=test";
$username = "username";
$password = "password";

$db = new DatabaseConnection($dsn, $username, $password);
$results = $db->query("SELECT * FROM table_name");