CHAPTER 3 ■ OBJECT BASICS
function getSummaryLine() {
$base = "{$this->title} ( {$this->producerMainName}, ";
$base .= "{$this->producerFirstName} )";
if ( $this->type == 'book' ) {
$base .= ": page count - {$this->numPages}";
} else if ( $this->type == 'cd' ) {
$base .= ": playing time - {$this->playLength}";
}
return $base;
}
In order to set the $type property, I could test the $numPages argument to the constructor. Still, once
again, the ShopProduct class has become more complex than necessary. As I add more differences to my
formats, or add new formats, these functional differences will become even harder to manage. Perhaps I
should try another approach to this problem.
Since ShopProduct is beginning to feel like two classes in one, I could accept this and create two
types rather than one. Here’s how I might do it:
class CdProduct {
public $playLength;
public $title;
public $producerMainName;
public $producerFirstName;
public $price;
function __construct( $title, $firstName,
$mainName, $price,
$playLength ) {
$this->title = $title;
$this->producerFirstName = $firstName;
$this->producerMainName = $mainName;
$this->price = $price;
$this->playLength = $playLength;
}
function getPlayLength() {
return $this->playLength;
}
function getSummaryLine() {
$base = "{$this->title} ( {$this->producerMainName}, ";
$base .= "{$this->producerFirstName} )";
$base .= ": playing time - {$this->playLength}";
return $base;
}
function getProducer() {
return "{$this->producerFirstName}".
" {$this->producerMainName}";
}
}
class BookProduct {