Inheritance
Inheritance is available in PHP4 and PHP5.
One of the powerful concepts in object-oriented programming is
inheritance. Inheritance allows a
new class to be defined by extending the capabilities of an existing
base class or parent class. PHP
allows a new class to be created by extending an existing class with the
extends keyword.
Example 4-7 shows how the UnitCounter class from Example 4-4 is extended to create the new class CaseCounter. The aim of the extended class is to track the number of cases or boxes that are needed to hold the units accumulated by the counter. For example, if bottles of wines are the units, then a case might hold 12 bottles.
Example 4-7. Defining the CaseCounter class by extending UnitCounter
<?php
// Access to the UnitCounter class definition
require "example.4-1.php";
class CaseCounter extends UnitCounter
{
var $unitsPerCase;
function addCase( )
{
$this->add($this->unitsPerCase);
}
function caseCount( )
{
return ceil($this->units/$this->unitsPerCase);
}
function CaseCounter($caseCapacity)
{
$this->unitsPerCase = $caseCapacity;
}
}
?>Before we discuss the implementation of the CaseCounter, we should examine the relationship with the UnitCounter class. Figure 4-1 illustrates this relationship in a simple class diagram . There are several different notations for representing class diagrams; we show the inheritance relationship by joining two classes with an annotated line with a solid arrowhead.
Figure 4-1. Class diagram showing UnitCounter and CaseCounter ...
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