PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 6 ■ OBJECTS AND DESIGN


Polymorphism


Polymorphism, or class switching, is a common feature of object-oriented systems. You have
encountered it several times already in this book.
Polymorphism is the maintenance of multiple implementations behind a common interface. This
sounds complicated, but in fact, it should be very familiar to you by now. The need for polymorphism is
often signaled by the presence of extensive conditional statements in your code.
When I first created the ShopProduct class in Chapter 3, I experimented with a single class which
managed functionality for books and CDs in addition to generic products. In order to provide summary
information, I relied on a conditional statement:


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;
}


These statements suggested the shape for the two subclasses: CdProduct and BookProduct.
By the same token, the conditional statements in my procedural parameter example contained the
seeds of the object-oriented structure I finally arrived at. I repeated the same condition in two parts of
the script.


function readParams( $source ) {
$params = array();
if ( preg_match( "/.xml$/i", $source )) {
// read XML parameters from $source
} else {
// read text parameters from $source
}
return $params;
}


function writeParams( $params, $source ) {
if ( preg_match( "/.xml$/i", $source )) {
// write XML parameters to $source
} else {
// write text parameters to $source
}
}


Each clause suggested one of the subclasses I finally produced: XmlParamHandler and
TextParamHandler, extending the abstract base class ParamHandler’s write() and read() methods.


// could return XmlParamHandler or TextParamHandler
$test = ParamHandler::getInstance( $file );


$test->read(); // could be XmlParamHandler::read() or TextParamHandler::read()
$test->addParam("key1", "val1" );
$test->write(); // could be XmlParamHandler::write() or TextParamHandler::write()

Free download pdf