What best practices should be followed when passing a PDO object to a class method for database operations in PHP?

When passing a PDO object to a class method for database operations in PHP, it is important to ensure that the PDO object is properly instantiated and passed by reference to the method. This helps maintain a single connection to the database throughout the application, improving performance and reducing resource usage. Additionally, using prepared statements with placeholders can help prevent SQL injection attacks and ensure data integrity.

class DatabaseHandler {
    private $pdo;

    public function __construct(PDO $pdo) {
        $this->pdo = $pdo;
    }

    public function fetchData($query) {
        $stmt = $this->pdo->prepare($query);
        $stmt->execute();
        return $stmt->fetchAll();
    }
}

$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
$dbHandler = new DatabaseHandler($pdo);

$data = $dbHandler->fetchData("SELECT * FROM my_table");