PHP OOP Interfaces

PHP Tutorial

 PHP OOP Interfaces

PHP OOP Interfaces

In PHP OOP Interfaces is like a pure blueprint.
It only contains method declarations, not method bodies.

A class that implements an interface must define all its methods.


What Interfaces Do?

  •  Force a class to follow a structure
  •  Define rules
  •  Allow multiple inheritance (a class can implement MANY interfaces)
  • Improve code architecture and flexibility

  Basic Interface Example


 


  Interface with Multiple Methods


 


 A Class Can Implement Multiple Interfaces


 

PHP does not support multiple class inheritance,
but supports multiple interface inheritance.


 Interface Methods Are Always Public

If you write:

In the implementing class, this is wrong:

Correct:


  Interface Constants

Interfaces can contain constants:

Use it like:


  Interface Extending Another Interface


  Practical Example – Payment Gateway


 


 Interface vs Abstract Class (Easy Table)

FeatureInterfaceAbstract Class
MethodsOnly abstract (PHP 7), allowed body in PHP 8Abstract + Normal
VariablesOnly constantsProperties allowed
Constructor NoYes
Multiple inheritance YesNo
Use caseDefine rulesBase class with partial implementation

 Summary (Easy to Remember)

ConceptMeaning
InterfaceBlueprint with method declarations
implementsA class follows the rules of interface
Must overrideAll methods must be defined
Multiple inheritanceClass can implement many interfaces

You may also like...