13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Implementing Inheritance in <strong>PHP</strong><br />

173<br />

Underst<strong>and</strong>ing Multiple Inheritance<br />

A few OO languages (most notably C++ <strong>and</strong> Smalltalk) support multiple inheritance,<br />

but like most, <strong>PHP</strong> does not.This means that each class can inherit from only one parent.<br />

No restrictions exist for how many children can share a single parent.What this<br />

means might not seem immediately clear. Figure 6.1 shows three different ways that<br />

three classes named A, B, <strong>and</strong> C can inherit.<br />

A<br />

A<br />

A<br />

B<br />

B<br />

C<br />

Single Inheritance<br />

B<br />

C<br />

Single Inheritance<br />

C<br />

Multiple Inheritance<br />

Figure 6.1<br />

<strong>PHP</strong> does not support multiple inheritance.<br />

The left combination shows class C inheriting from class B, which in turn inherits from<br />

class A. Each class has at most one parent, so this is a perfectly valid single inheritance<br />

in <strong>PHP</strong>.<br />

The center combination shows classes B <strong>and</strong> C inheriting from class A. Each class has<br />

at most one parent, so again this is a valid single inheritance.<br />

The right combination shows class C inheriting from both class A <strong>and</strong> class B. In this<br />

case, class C has two parents, so this is a case of multiple inheritance <strong>and</strong> is invalid in<br />

<strong>PHP</strong>.<br />

Implementing Interfaces<br />

If you need to implement the functionality seen in instances of multiple inheritance, you<br />

can do so in <strong>PHP</strong> through interfaces.They are seen as workarounds for multiple inheritance<br />

<strong>and</strong> are similar to the interface implementation supported by other object-oriented<br />

languages, including Java.<br />

The idea of an interface is that it specifies a set of functions that must be implemented<br />

in classes that implement that interface. For instance, you might decide that you have<br />

a set of classes that need to be able to display themselves. Instead of having a parent class<br />

with a display() function that they all inherit from <strong>and</strong> override, you can implement<br />

an interface as follows:<br />

interface Displayable<br />

{

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!