Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

tiendungdev's avatar

tiendungdev liked a comment+100 XP

4w ago

Object-Oriented Principles in PHP: Ep 4, Dependencies, Coupling, and Interfaces

This is what made it click for me:

So $this->gateway->charge($amount); in the invoice class could be interpreted as - in case of a PaypalGateway object - as PaypalGateway ->charge(amount)?

Yes, that's correct! The line $this->gateway->charge($amount); in the Invoice class is a call to the charge method of the object that was injected into the Invoice class via its constructor.

Let's break it down step by step:

  1. Dependency Injection:

    • When you create an instance of the Invoice class, you pass an object that implements the BillingGateway interface to its constructor. For example:
      $paypalGateway = new PaypalGateway();
      $invoice = new Invoice($paypalGateway);
      
    • In this case, $paypalGateway is an instance of the PaypalGateway class, which implements the BillingGateway interface.
  2. Constructor Assignment:

    • Inside the Invoice class constructor, the passed BillingGateway object is assigned to the $gateway property:
      public function __construct(BillingGateway $gateway)
      {
          $this->gateway = $gateway;
      }
      
    • So, $this->gateway now refers to the $paypalGateway object.
  3. Method Call:

    • When you call $this->gateway->charge($amount); in the pay method of the Invoice class, it is equivalent to calling $paypalGateway->charge($amount); because $this->gateway is the $paypalGateway object.
    • The charge method of the PaypalGateway class will be executed with the $amount parameter.

Example Walkthrough:

Output:

Charging 100 using PayPal.

Explanation:

  • The PaypalGateway instance is created and passed to the Invoice constructor.
  • The Invoice class stores this instance in its $gateway property.
  • When the pay method of the Invoice class is called with an amount, it calls the charge method on the PaypalGateway instance stored in $this->gateway.
  • The charge method of the PaypalGateway class is executed, printing the message "Charging 100 using PayPal."

This demonstrates how dependency injection allows the Invoice class to use any implementation of the BillingGateway interface without being tightly coupled to a specific implementation.