What are the advantages of using Dependency Injection for passing database objects to classes in PHP?

When passing database objects to classes in PHP, using Dependency Injection can help improve code reusability, maintainability, and testability. By injecting the database object into the class constructor or method, we can easily swap out different database implementations or mock objects for testing purposes without tightly coupling the class to a specific database instance.

// Example of using Dependency Injection to pass database object to a class

class Database {
    // Database connection details
}

class UserRepository {
    private $db;

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

    public function getUserById($id) {
        // Database query using $this->db
    }
}

// Usage
$database = new Database();
$userRepository = new UserRepository($database);
$user = $userRepository->getUserById(1);