2.2. Inheritance and Interfaces

One of the benefits to using OOP with PHP5 is that it allows you to break down your code into logical chunks, in order to facilitate reuse. These chunks, when carefully written, can be reused again and again, in many different projects, leaving the programmer free to write code that is specific to the problem he or she is trying to solve.

In OOP, there are a couple of ways in which a group of methods and properties can be specified for use in multiple classes. The first, inheritance, allows you to define a base set of properties and methods that belong to a base class, and can be used as a building block for more specific classes. The second, interfaces, allow you prescribe a list of methods that a class must implement.

2.2.1. Inheritance

Suppose you are creating a code library, one for manipulation of different geometric shapes. The Circle class that you've been using throughout the chapter could be part of that very library. In creating different classes for different shapes—square, circle, triangle, and so on—you may find that you're duplicating methods that are similar or identical among all shapes. This would be a good opportunity to use inheritance.

2.2.1.1. The extends Keyword

Assume that all of the geometric shape classes are going to be drawn on a grid. Therefore, they will all need some sort of origin point (x,y). You could include an origin property in each of the different classes, or using the extends keyword, you could use inheritance ...

Get Professional LAMP: Linux®, Apache, MySQL®, and PHP5 Web Development 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.