When do we need Interfaces in PHP?
Interface are definitions of the public APIs that classes (implementing an interface) must implement. It is also known as contracts as an interface allows to specify a list of methods that a class must implement. Interface definition is similar to the class definition, just by changing the keyword class to interface.
Interfaces can contain methods and/or constants, but no attributes. Interface constants have the same restrictions as class constants. Interface methods are implicitly abstract.
Any class that needs to implement an interface must do using the implements keyword. A single class can implement more than one interface at a time.
Interesting Points :
- A class cannot implement two interfaces that have the same method name because it would end up with the method ambiguity.
- Like classes, it is possible to establish an inheritance relationship between interfaces by using the same keyword “extends”.
Below is a complete example that shows how interfaces work.
GeeksforGeeks green Triangle
Importance of using Interfaces:
- Interface provide a flexible base/root structure that you don’t get with classes.
- By implementing interface the caller of the object need to care only about the object’s interface not implementations of the object’s methods.
- Interface allows unrelated classes to implement the same set of methods regardless of their positions in the class inheritance hierarchy.
- Interface enables you to model multiple inheritance.