How can the issue of passing database resources between classes be resolved using PHP best practices?

When passing database resources between classes in PHP, it is best practice to use Dependency Injection to inject the database connection into the classes that need it. This helps decouple the database connection from the classes, making the code more maintainable and testable.

// Database connection class
class Database {
    private $connection;

    public function __construct($host, $username, $password, $database) {
        $this->connection = new mysqli($host, $username, $password, $database);
    }

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

// Class that requires database connection
class MyClass {
    private $db;

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

    public function fetchData() {
        $connection = $this->db->getConnection();
        // Code to fetch data from database using $connection
    }
}

// Usage
$database = new Database('localhost', 'username', 'password', 'database');
$myClass = new MyClass($database);
$myClass->fetchData();