40. Interfaces and Polymorphism
Interfaces provide another powerful way to enforce structure. They define a contract: any class implementing an interface must implement all the methods listed in that interface.
Defining an Interface
- Defined using the
interfacekeyword. - All methods in an interface must be public.
- Interfaces contain only method signatures, no logic or properties (except constants).
php
<?php interface PaymentGateway { public function processPayment($amount); public function refundTransaction($id); // No method body allowed! } ?>Implementing an Interface
A class uses the implements keyword to adopt an interface. If it fails to implement all required methods, it results in a fatal error.
php
<?php class StripeGateway implements PaymentGateway { public function processPayment($amount) { // Stripe specific logic... echo "Stripe processing $amount dollars."; } public function refundTransaction($id) { // Stripe specific logic... echo "Stripe refunding transaction $id."; } } class PayPalGateway implements PaymentGateway { public function processPayment($amount) { // PayPal specific logic... echo "PayPal processing $amount dollars."; } public function refundTransaction($id) { // PayPal specific logic... echo "PayPal refunding transaction $id."; } } ?>Polymorphism in Action
Since both classes implement the same interface, we can use them interchangeably, relying on the common method signatures (processPayment). This is polymorphism.
php
<?php function handleTransaction(PaymentGateway $gateway, $amount) { // We don't care IF it's Stripe or PayPal, only that it has the method. $gateway->processPayment($amount); } handleTransaction(new StripeGateway(), 500); handleTransaction(new PayPalGateway(), 250); ?>