PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 3 ■ OBJECT BASICS

function setArray( array $storearray ) {
$this->array = $storearray;
}


Support for array hinting was added to the language with version 5.1. Support for null default values
in hinted arguments was another late addition. This means that you can demand either a particular type
or a null value in an argument. Here’s how:


function setWriter( ObjectWriter $objwriter=null ) {
$this->writer = $objwriter;
}


So far, I have discussed types and classes as if they were synonymous. There is a key difference,
however. When you define a class you also define a type, but a type can describe an entire family of
classes. The mechanism by which different classes can be grouped together under a type is called
inheritance. I discuss inheritance in the next section.


Inheritance


Inheritance is the means by which one or more classes can be derived from a base class.
A class that inherits from another is said to be a subclass of it. This relationship is often described in
terms of parents and children. A child class is derived from and inherits characteristics from the parent.
These characteristics consist of both properties and methods. The child class will typically add new
functionality to that provided by its parent (also known as a superclass); for this reason, a child class is
said to extend its parent.
Before I dive into the syntax of inheritance, I’ll examine the problems it can help you to solve.


The Inheritance Problem


Look again at the ShopProduct class. At the moment, it is nicely generic. It can handle all sorts of
products.


$product1 = new ShopProduct( "My Antonia", "Willa", "Cather", 5.99 );
$product2 = new ShopProduct( "Exile on Coldharbour Lane",
"The", "Alabama 3", 10.99 );
print "author: ".$product1->getProducer()."\n";
print "artist: ".$product2->getProducer()."\n";


Here’s the output:

author: Willa Cather
artist: The Alabama 3


Separating the producer name into two parts works well with both books and CDs. I want to be able
to sort on “Alabama 3” and “Cather”, not on “The” and “Willa”. Laziness is an excellent design strategy,
so there is no need to worry about using ShopProduct for more than one kind of product at this stage.
If I add some new requirements to my example, however, things rapidly become more complicated.
Imagine, for example, that you need to represent data specific to books and CDs. For CDs, you must
store the total playing time; for books, the total number of pages. There could be any number of other
differences, but these will serve to illustrate the issue.

Free download pdf