PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 3 ■ OBJECT BASICS


$base = "$this->title ( {$this->producerMainName}, ";
$base .= "{$this->producerFirstName} )";
return $base;
}
}


class CdProduct extends ShopProduct {
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 {
function getNumberOfPages() {
return $this->numPages;
}


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


To create a child class, you must use the extends keyword in the class declaration. In the example, I
created two new classes, BookProduct and CdProduct. Both extend the ShopProduct class.
Because the derived classes do not define constructors, the parent class’s constructor is
automatically invoked when they are instantiated. The child classes inherit access to all the parent’s
public and protected methods (though not to private methods or properties). This means that you can
call the getProducer() method on an object instantiated from the CdProduct class, even though
getProducer() is defined in the ShopProduct class.


$product2 = new CdProduct( "Exile on Coldharbour Lane",
"The", "Alabama 3",
10.99, null, 60.33 );
print "artist: {$product2->getProducer()}\n";


So both the child classes inherit the behavior of the common parent. You can treat a BookProduct
object as if it were a ShopProduct object. You can pass a BookProduct or CdProduct object to the
ShopProductWriter class’s write() method and all will work as expected.
Notice that both the CdProduct and BookProduct classes override the getSummaryLine() method,
providing their own implementation. Derived classes can extend but also alter the functionality of their
parents.
The super class’s implementation of this method might seem redundant, because it is overridden by
both its children. Nevertheless it provides basic functionality that new child classes might use. The
method’s presence also provides a guarantee to client code that all ShopProduct objects will provide a

Free download pdf