PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 3 ■ OBJECT BASICS

}


$str = "{$shopProduct->title}: ".
$shopProduct->getProducer().
" ({$shopProduct->price})\n";
print $str;
}
}


Notice the instanceof operator in the example; instanceof resolves to true if the object in the left-
hand operand is of the type represented by the right-hand operand.
Once again, I have been forced to include a new layer of complexity. Not only do I have to test the
$shopProduct argument against two types in the write() method but I have to trust that each type will
continue to support the same fields and methods as the other. It was all much neater when I simply
demanded a single type because I could use class type hinting, and because I could be confident that the
ShopProduct class supported a particular interface.
The CD and book aspects of the ShopProduct class don’t work well together but can’t live apart, it
seems. I want to work with books and CDs as a single type while providing a separate implementation
for each format. I want to provide common functionality in one place to avoid duplication but allow
each format to handle some method calls differently. I need to use inheritance.


Working with Inheritance


The first step in building an inheritance tree is to find the elements of the base class that don’t fit
together or that need to be handled differently.
I know that the getPlayLength() and getNumberOfPages() methods do not belong together. I also
know that I need to create different implementations for the getSummaryLine() method. Let’s use these
differences as the basis for two derived classes:


class ShopProduct {
public $numPages;
public $playLength;
public $title;
public $producerMainName;
public $producerFirstName;
public $price;


function __construct( $title, $firstName,
$mainName, $price,
$numPages=0, $playLength=0 ) {
$this->title = $title;
$this->producerFirstName = $firstName;
$this->producerMainName = $mainName;
$this->price = $price;
$this->numPages = $numPages;
$this->playLength = $playLength;
}


function getProducer() {
return "{$this->producerFirstName}".
" {$this->producerMainName}";
}


function getSummaryLine() {

Free download pdf