PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 3 ■ OBJECT BASICS

getSummaryLine() method. Later on you will see how it is possible to make this promise in a base class
without providing any implementation at all. Each child ShopProduct class inherits its parent’s
properties. Both BookProduct and CdProduct access the $title property in their versions of
getSummaryLine().
Inheritance can be a difficult concept to grasp at first. By defining a class that extends another, you
ensure that an object instantiated from it is defined by the characteristics of first the child and then the
parent class. Another way of thinking about this is in terms of searching. When I invoke $product2-



getProducer(), there is no such method to be found in the CdProduct class, and the invocation falls
through to the default implementation in ShopProduct. When I invoke $product2->getSummaryLine(), on
the other hand, the getSummaryLine() method is found in CdProduct and invoked.
The same is true of property accesses. When I access $title in the BookProduct class’s
getSummaryLine() method, the property is not found in the BookProduct class. It is acquired instead from
the parent class, from ShopProduct. The $title property applies equally to both subclasses, and
therefore, it belongs in the superclass.
A quick look at the ShopProduct constructor, however, shows that I am still managing data in the
base class that should be handled by its children. The BookProduct class should handle the $numPages
argument and property, and the CdProduct class should handle the $playLength argument and property.
To make this work, I will define constructor methods in each of the child classes.



Constructors and Inheritance


When you define a constructor in a child class, you become responsible for passing any arguments on to
the parent. If you fail to do this, you can end up with a partially constructed object.
To invoke a method in a parent class, you must first find a way of referring to the class itself: a
handle. PHP provides us with the parent keyword for this purpose.
To refer to a method in the context of a class rather than an object you use :: rather than ->. So


parent::__construct()


means “Invoke the __construct() method of the parent class.” Here I amend my example so that each
class handles only the data that is appropriate to it:


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


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


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


function getSummaryLine() {
$base = "{$this->title} ( {$this->producerMainName}, ";

Free download pdf