PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 3 ■ OBJECT BASICS


$base .= "{$this->producerFirstName} )";
return $base;
}
}


class CdProduct extends ShopProduct {
public $playLength;


function construct( $title, $firstName,
$mainName, $price, $playLength ) {
parent::
construct( $title, $firstName,
$mainName, $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;
}
}


class BookProduct extends ShopProduct {
public $numPages;


function construct( $title, $firstName,
$mainName, $price, $numPages ) {
parent::
construct( $title, $firstName,
$mainName, $price );
$this->numPages = $numPages;
}


function getNumberOfPages() {
return $this->numPages;
}


function getSummaryLine() {
$base = "$this->title ( $this->producerMainName, ";
$base .= "$this->producerFirstName )";
$base .= ": page count - $this->numPages";
return $base;
}
}


Each child class invokes the constructor of its parent before setting its own properties. The base
class now knows only about its own data. Child classes are generally specializations of their parents. As a
rule of thumb, you should avoid giving parent classes any special knowledge about their children.

Free download pdf