How can dependency injection be implemented in PHP to pass database access objects to different classes and methods?

To implement dependency injection in PHP for passing database access objects to different classes and methods, you can create a database connection class that creates the database connection object. Then, inject this database connection object into the classes or methods that need to access the database.

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

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

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

// Example class using dependency injection
class UserRepository {
    private $db;

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

    public function getUserById($id) {
        $stmt = $this->db->getConnection()->prepare("SELECT * FROM users WHERE id = :id");
        $stmt->bindParam(':id', $id);
        $stmt->execute();
        return $stmt->fetch();
    }
}

// Create a new database connection
$db = new Database('localhost', 'username', 'password', 'database');

// Create a new instance of UserRepository with the injected database connection
$userRepository = new UserRepository($db);

// Example usage
$user = $userRepository->getUserById(1);