Object Oriented PHP: Part 5

In case you haven't been reading, here is the series so far:

Inheritance

Inheritance is the method in which a class is derived from another class, called a parent class. An inherited class works like this:


class SalesItem {\n
public $brand;\n
public $name;\n
public $price = 0;\n
\n
function __construct( $brand, $name, $price ) {\n
$this -> brand = $brand;\n
$this -> name = $name;\n
$this -> price = $price;\n
}\n
\n
function getSummary() {\n
$summary = "{$this -> brand}" . " {$this -> name}";\n
return $summary;\n
}\n
}\n
\n
class MP3Item extends SalesItem {\n
public $bitrate;\n
\n
function __construct( $brand, $name, $price, $bitrate ) {\n
parent::__construct( $brand, $name, $price );\n
$this -> bitrate = $bitrate;\n
}\n
\n
function getSummary() {\n
$summary = parent::getSummary();\n
$summary .= ", bitrate: {$this -> bitrate}";\n
return $summary;\n
}\n
\n
}\n

So what have we here? Note slight changes in the SalesItem class. First, we implement inheritance using the extends keyword. The new sub class looks much like its super class. Creating an instance of the MP3Item class invokes the constructor of both it and it's parent class via the parent::_constructor line. A class can invoke any public or protected method of a parent class using the parent:: keyword. The parent's method is again invoked in the getSummary method and additional information is concatenated.

The great thing about inheritance is that it allows any number of branch classes that extend the super class. We could build another class for LP records.


class LPItem extends SalesItem {\n
public $rpm;\n
\n
function __construct( $brand, $name, $price, $bitrate ) {\n
parent::__construct( $brand, $name, $price );\n
$this -> bitrate = $bitrate;\n
}\n
\n
function getSummary() {\n
$summary = parent::getSummary();\n
$summary .= ", table speed: {$this -> rpm}";\n
return $summary;\n
}\n
\n
}\n

So there you go, we have learned to use the extends keyword to implement inheritance and the parent:: keyword to invoke methods belonging to a class' parent class.

Next time we will look at using access modifiers to control access to a classes methods and how it relates to inheritance.

User login

Contacting Rob

Y! roberthenrylowe
AIM roberthenrylowe
ICQ 249971225
email rhlowe [at] gmail dot com

Networking Links