Simulating multiple inheritance with interfaces in PHP



An interface is very similar to an abstract class, but it has no properties and cannot define how methods are to be implemented. Instead, it is simply a list of methods that must be implemented. Moreover, all methods must be public. While this sounds strange, it has two main purposes, namely:

1) An interface ensures that all classes that implement it have a common set of functionality.

2) Although a child class can have only one parent, it can implement multiple interfaces.


This second characteristic is what makes interfaces very powerful. An interface offers a way of inheriting from a single parent while sharing an extra set of common features that don’t necessarily apply to all child classes.

To create an interface, use the interface keyword followed by the name of the interface and a pair or curly braces. Inside the braces, declare the methods without defining their contents. A common convention is to prefix the name of an interface with an uppercase I, but the Zend Framework PHP coding standard that I am following ends the name with _Interface instead. Because the coding standard maps class and interface names to the directory structure, an interface called Ch2_Downloads_Interface would be stored as Interface.php in a folder called Ch2/Downloads. This can result in a large directory structure, but it has the advantage of consistency and clarity. However, you can choose whichever convention you like. An interface for downloadable items may look something like this:

interface Ch2_Downloads_Interface
{
public function getFileLocation();
public function createDownloadLink();
}


To use an interface, include it automatically with __autoload() or manually with require_once and follow the class name with the keyword implements and the name of the interface in the class definition like this (since I haven’t implemented the methods, there are no download files for this example):

require_once 'Downloads/Interface.php';
class Ch2_Ebook extends Ch2_Product implements Ch2_Downloads_Interface
{
// properties and other methods
public function getFileLocation()
{
// details of method
}
public function createDownloadLink()
{
// details of method
}
}


A class can implement multiple interfaces. Just list them as a comma-delimited list after the implementskeyword.