Skip to content
PHP Logo

What are some key differences between Constructor Injection and Method Injection in PHP, and when should each be used for managing class dependencies?

Constructor Injection involves passing dependencies to a class through its constructor, while Method Injection involves passing dependencies to specific methods as arguments. Constructor Injection is typically used for mandatory dependencies that are required for the class to function properly, while Method Injection is used for optional dependencies or dependencies that are only needed for specific methods.

php
// Constructor Injection example
class UserService {
    private $userRepository;

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

    public function getUserById($userId) {
        return $this->userRepository->getUserById($userId);
    }
}

// Method Injection example
class PaymentService {
    public function processPayment(PaymentGateway $paymentGateway, $amount) {
        $paymentGateway->processPayment($amount);
    }
}