Interfaces

If you had a Boat class and a Plane class, how would you implement a Boatplane class? The methods found in Boat would be helpful to give you code such as sink(), scuttle(), dock(), etc., and the methods found in Plane would be helpful to give you code such as takeoff(), land(), and bailout(). What is really needed here is the ability to inherit from both the Boat class and the Plane class, a technique known as multiple inheritance .

Sadly, PHP has no support for multiple inheritance, which means it is a struggle to implement this particular scenario. The solution is to use interfaces , which can be thought of as abstract classes where you can define sets of abstract methods that will be used elsewhere. If we were to use interfaces in the above example, both boat and plane would be interfaces, and class Boatplane would implement both of these interfaces. A class that implements an interface has to have concrete methods for each of the abstract methods defined in the interface, so by making a class implement an interface, you are in fact saying, "This class is able to do everything the interface says it should." In essence, using interfaces is a way to form contracts with your classes—they must implement methods A, B, and C; otherwise, they will not work.

The above example could be written using interfaces like this:

 interface Boat { function sink(); function scuttle(); function dock(); } interface Plane { function takeoff(); function land(); function bailout(); } class ...

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.