I am trying to improve my knowledge of OOP in PHP and have been researching abstract classes and interfaces.
What I have learned
- They are both classes that cannot be instantiated themselves but can olny be extended (implemented in the case of interfaces)
- Abstract classes provide methods and properties for other classes that extend them.
- If a class uses an abstract method then the class itself must also be abstract.
- If an abstract method is defined within an abstract class, all child classes must define the details of that method. Methods not defined as abstract can be used in the same way as normal methods.
- Interfaces define what methods a class that implements it must have. The functionality of the methods are not defined in the interface, the interface just offers a list of methods that must be included in the child class.
- An interface does not define any properties.
- Classes can implement as many interfaces as they want to but they must define a method for every one of the interfaces they implement
I think that covers the basics. Please feel free to add to that if you think there’s anything I have missed.
What I would like to know is if there are any real world examples of implementation of these classes, especially the interface class. Does anyone know of any open source applications that use them that I can browse to better understand them and see where and when they are used effectively? I have come across book examples which use animals which fails to demonstrate the importance of these classes.
Not a real world example as such, but one Design Pattern where you usually encounter interfaces and abstract classes is the Command Pattern. See link for example code.
In general, “programming against an interface” is considered good OO practise, because it decouples concrete implementations and let you more easily change them for other implementations, e.g. instead of asking for a specific class
you just ask that it provides a certain set of methods
Interfaces also help teasing apart large inheritance structures. Because PHP supports only Single Inheritance, you’ll often see hierarchies like this:
where each of these contains specific aspects used inside these classes. With an interface, you just do
and then include that specific code via Strategy Patterns or Composition/Aggregation, which is ultimately much more maintainable.
For a list of predefined interfaces in PHP see my answer to: