PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 3 ■ OBJECT BASICS

Note Prior to PHP 5, constructors took on the name of the enclosing class. The new unified constructors use the


name __construct(). Using the old syntax, a call to a parent constructor would tie you to that particular class:


parent::ShopProduct();


This could cause problems if the class hierarchy changed. Many bugs result from programmers changing the


immediate parent of a class but forgetting to update the constructor. Using the unified constructor, a call to the


parent constructor, parent::__construct(), invokes the immediate parent, no matter what changes are made in


the hierarchy. Of course, you still need to ensure that the correct arguments are passed to an inserted parent!


Invoking an Overridden Method


The parent keyword can be used with any method that overrides its counterpart in a parent class. When
you override a method, you may not wish to obliterate the functionality of the parent but rather extend
it. You can achieve this by calling the parent class’s method in the current object’s context. If you look
again at the getSummaryLine() method implementations, you will see that they duplicate a lot of code. It
would be better to use rather than reproduce the functionality already developed in the ShopProduct
class.


// ShopProduct class...
function getSummaryLine() {
$base = "{$this->title} ( {$this->producerMainName}, ";
$base .= "{$this->producerFirstName} )";
return $base;
}


// BookProduct class...
function getSummaryLine() {
$base = parent::getSummaryLine();
$base .= ": page count - {$this->numPages}";
return $base;
}


I set up the core functionality for the getSummaryLine() method in the ShopProduct base class.
Rather than reproduce this in the CdProduct and BookProduct subclasses, I simply call the parent method
before proceeding to add more data to the summary string.
Now that you have seen the basics of inheritance, I will reexamine property and method visibility in
light of the full picture.


Public, Private, and Protected: Managing Access to Your Classes


So far, I have declared all properties public, implicitly or otherwise. Public access is the default setting
for methods and for properties if you use the old var keyword in your property declaration.
Elements in your classes can be declared public, private, or protected:



  • Public properties and methods can be accessed from any context.

  • A private method or property can only be accessed from within the enclosing
    class. Even subclasses have no access.

Free download pdf