Abstract Classes and Interfaces
When developing class hierarchies, it's often useful to insert extra classes to help logically organize code or to provide a base for polymorphic behavior.
The abstract keyword
Abstract classes are available in PHP5.
In Example 14-1, we defined a set of related classes to describe shapes that includes a base class Shape and its two member functions color( ) and sides( ). Let's suppose we want to add a function area( ) that calculates the area of a shape. If we want to allow the area to be calculated for all Shape objects, then the function must be made available in the Shape class.
However, unlike the color(
) and sides( )
functions, the area( )
function can only be implemented in the descendant classes because
area calculations vary from shape to shape. The area of a circle is
calculated using the radius, while a rectangle uses height and width,
and so on. Using the abstract
keyword, PHP5 allows you to define member functions without having to
define an implementation. However, a class that contains an abstract
function can't be used to create objects, and must also be defined as
abstract. Example 14-2
shows how the Shapes class is
redefined to include the abstract area(
) function.
Example 14-2. An abstract base class
<?php abstract class Shape { var $color; var $sides; function color( ) { return $this->color; } function sides( ) { return $this->sides; } abstract function area( ); function _ _construct($color, $sides) { $this->color = $color; $this->sides ...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.
Read now
Unlock full access