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
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
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
processPayment($amount); } handleTransaction(new StripeGateway(), 500); handleTransaction(new PayPalGateway(), 250); ?>