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:
- compile-time (overloading)
- 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
The class which uses or implements PaymentCollectionIterface en-forces the class to implement the collect method.
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.
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.
if user want to pay with stripe then you can do like this below.
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
Top comments (0)