What are the advantages of using dependency injection in PHP and how can it improve code maintainability and testability?

Dependency injection in PHP allows for better code maintainability and testability by decoupling components and making them easier to replace or modify. It also promotes code reusability and helps in following the SOLID principles of object-oriented design.

// Before using dependency injection
class UserService {
    private $userRepository;

    public function __construct() {
        $this->userRepository = new UserRepository();
    }
}

// After using dependency injection
class UserService {
    private $userRepository;

    public function __construct(UserRepository $userRepository) {
        $this->userRepository = $userRepository;
    }
}