Page 237 - Beginning PHP 5.3
P. 237
Chapter 8: Objects
Taking the previous Fruit and Grape example, say you want to create a Banana class that extends the
Fruit class. Generally, you consume a banana like any other fruit, but you also need to break the banana
off from a bunch of bananas first. So within your Banana class, you can override the parent ’ s consume()
method to include functionality to break off a banana, then call the overridden consume() method from
within the Banana class ’ s consume() method to finish the consumption process:
class Banana extends Fruit {
public function consume() {
echo “ < p > I’m breaking off a banana... < /p > ”;
parent::consume();
}
}
$banana = new Banana;
$banana- > consume();
This code produces the following output:
I’m breaking off a banana...
I’m peeling the fruit...
I’m slicing the fruit...
I’m eating the fruit. Yummy!
Blocking Inheritance and Overrides with Final
Classes and Methods
By now you probably realize that being able to extend a class with inheritance is one of the more
powerful aspects of OOP. Generally speaking, there ’ s no problem with allowing your classes to be
extended in this way (by you or by other programmers).
However, occasionally it ’ s useful to be able to lock down a class so that it can ’ t be inherited from.
Similarly, you might want to lock down one or more methods inside a class so that they can ’ t be
overridden in a child class. By doing this, you know that your class — or methods within your class —
will always behave in exactly the same way.
You can add the keyword final before a class or method definition to lock down that class or method.
For example, here ’ s how to create a final class:
final class HandsOffThisClass {
public $someProperty = 123;
public function someMethod() {
echo “A method”;
}
}
// Generates an error:
// “Class ChildClass may not inherit from final class (HandsOffThisClass)”
class ChildClass extends HandsOffThisClass {
}
199
9/21/09 9:03:42 AM
c08.indd 199
c08.indd 199 9/21/09 9:03:42 AM