Chapter 14. Advanced Features of Object-Oriented Programming in PHP 5
In Chapter 4, we introduced the basic concepts of object-oriented programming, showing how classes are defined and how objects are created and used with PHP. The techniques shown in Chapter 4 can be used to help build reusable, modular code, and are applicable when using object-oriented packages such as the PEAR packages we describe in Chapter 7. However, much of the power of object-oriented programming doesn't come from simply reusing code.
In this chapter, we show some more powerful techniques available with object-oriented programming, including:
Class hierarchies
Polymorphic behavior
Class type hints
Abstract classes and interfaces
Working with Class Hierarchies
In Chapter 4, we
showed you how inheritance can be used as a powerful tool in
object-oriented programming. Using the extends
keyword, a class can inherit the capabilities from a
parent class. As we explained in Chapter 4, PHP allows an inheritance
from only one parent class, but a class can be extended to create any
number of child classes.
Inheritance allows functionality to be built up from related classes. Each class provides specialized support that's specific to a class's purpose. It's common that functionality in an object-oriented application is provided by class hierarchies rather than single, unrelated classes.
Example 14-1 shows how a class hierarchy is formed to provide functionality that describes shapes.
Example 14-1. Shape classes
<?php class ...
Get Web Database Applications with PHP and MySQL, 2nd Edition 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.