DEV Community

Saravana Sai
Saravana Sai

Posted on

Interfaces and Polymorphism in PHP - Practical Guide

Polymorphism

Polymorphism in OOP's is a concept that allows you to create classes with different functionalities in a single interface generally, it is of two types:

  1. compile-time (overloading)
  2. run time (overriding)

But polymorphism in PHP does not support overloading, or in other words, compile-time polymorphism.

! Let don’t have to worry about the technicalities & jargon's. Let see a example with a explanation.

Scenario:

Let consider that we have to write a code for payment gateway integration & they may be more than one payment gateway (stripe & pay-pal) . The different users may choose different payment method & also in future there may be a some other payment methods also.

Just take a min & roll up you heads for a solution . There are different ways to approach this with simple if-else condition but by using a PHP interface we can get a clean implementation.

let's create an interface

Image description

The class which uses or implements PaymentCollectionIterface en-forces the class to implement the collect method.

Image description

Image description

StripePaymentService implements PaymentCollectionIterface
as well as for PaypalPaymentService.

Don't take the implementation part of collect method so seriously that is just an example. Let's focus on a problem. Till now we have a two separate class for each payment method.

Now let's create a PaymentService class which handle the payment detection logic.

Image description

In above code we have type hinted the
CollectAmount(PaymentCollectionIterface $collector) method with PaymentCollectionIterface.This is where the polymorphism come in to play.The argument passed to the CollectAmount() method should the the instance of a class which implements the PaymentCollectionIterface else it will throw an error.

As we know that both StripePaymentService & PaypalPaymentService implements PaymentCollectionIterface. So , PHP is smart enough to resolve that collect method on the class which the instance is passed.

It resolves the payment method on run time.Now if user want to pay with paypal.you can invoke a paymentService class like below.

Image description

if user want to pay with stripe then you can do like this below.

Image description

Conclusion

... So that's it a Interfaces and Polymorphism in PHP using in a more practical way

Hopefully this will be useful to some of you :)

I'd love to hear what you're comments & more example let me know in the comments below!

Follow for more content like this & share

Latest comments (0)