What are the potential drawbacks of passing database resources between classes in PHP?

Passing database resources between classes in PHP can lead to tightly coupled code, making it harder to maintain and test. It can also result in potential resource leaks if the database connection is not properly closed. To solve this issue, it's better to encapsulate the database connection within a single class and use dependency injection to pass the database object to other classes that need it.

class Database {
    private $connection;

    public function __construct() {
        $this->connection = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
    }

    public function getConnection() {
        return $this->connection;
    }
}

class MyClass {
    private $db;

    public function __construct(Database $db) {
        $this->db = $db;
    }

    public function someMethod() {
        $stmt = $this->db->getConnection()->prepare("SELECT * FROM table");
        $stmt->execute();
        // Do something with the results
    }
}

// Usage
$database = new Database();
$myClass = new MyClass($database);
$myClass->someMethod();