PHP - Interface Polymorphism

Interface polymorphism in PHP is a concept that enables different classes to be treated as instances of a common interface. This allows you to write code that can work with various objects in a unified manner, as long as they adhere to the methods specified in the interface. Interface polymorphism helps achieve a high level of abstraction and promotes code reusability.

Defining an Interface:

interface PaymentGateway {
  public function processPayment($amount);
}

In this example, the PaymentGateway interface defines a contract that classes must adhere to. It specifies that any class implementing this interface must provide a processPayment method.

Implementing the Interface:

class PayPal implements PaymentGateway {
  public function processPayment($amount) {
      // PayPal-specific implementation
  }
}
class CreditCard implements PaymentGateway {
  public function processPayment($amount) {
      // Credit card-specific implementation
  }
}

Both the PayPal and CreditCard classes implement the PaymentGateway interface. This means that they must provide an implementation for the processPayment method specified in the interface.

Using Interface Polymorphism:

function makePayment(PaymentGateway $gateway, $amount) {
    $gateway->processPayment($amount);
}
$paypal = new PayPal();
$creditCard = new CreditCard();
makePayment($paypal, 100);       // Process payment via PayPal
makePayment($creditCard, 50);    // Process payment via Credit Card

In this example, the makePayment function takes an object that implements the PaymentGateway interface as its first argument. This allows you to pass either a PayPal or a CreditCard object to the function, as long as they adhere to the methods specified in the interface. This demonstrates interface polymorphism, where different objects with varying implementations can be treated uniformly based on their shared interface.

Key points about interface polymorphism:

Interfaces define a contract that classes must fulfill by providing method implementations.

Multiple classes can implement the same interface, enabling polymorphism.

Interface polymorphism promotes code reusability and ensures a consistent way of interacting with different objects.

The code that interacts with objects through interfaces doesn't need to know the specific class implementations; it works based on the interface contract.

Interfaces are particularly useful when you want to define common behavior for different classes that might not share the same inheritance hierarchy.

Interface polymorphism is a powerful mechanism in PHP that allows you to design flexible and maintainable code by promoting a separation of concerns and a clear definition of contracts.