Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page