Page 234 - Beginning PHP 5.3
P. 234
Part II: Learning the Language
H ow I t W orks
The script first creates the parent Shape class. This class contains just the properties and methods
common to all shapes. It contains private properties to store the shape ’ s color and record whether the
shape is filled or hollow, then provides public accessor methods to get and set the color, as well as fill
the shape or make it hollow and retrieve the shape ’ s fill status.
Next, the script creates a Circle class that inherits from the Shape class. Remember that a child class
inherits all the properties and methods of its parent. The Circle class also adds a private property to
store the circle ’ s radius, and provides public methods to get and set the radius, as well as calculate the
area from the radius using the formula π r .
2
The script then creates Square , another class that inherits from Shape . This time, the class adds a
private property to track the length of one side of the square, and provides methods to get and set the
2
side length and calculate the square ’ s area using the formula (side length) .
Finally, the script demonstrates the use of the Circle and Square classes. First it creates a new
Circle object, sets its color, fills it, and sets its radius to 4. It then displays all the properties of
the circle, and calculates its area using the getArea() method of the Circle class. Notice how the
script calls some methods that are in the parent Shape class, such as setColor() and isFilled() ,
and some methods that are in the child Circle class, such as setRadius() and getArea() .
The script then repeats the process with the Square class, creating a hollow green square with a side
length of 3, then displaying the square ’ s properties and calculating its area using the Square class ’ s
getArea() method.
Overriding Methods in the Parent Class
What if you want to create a child class whose methods are different from the corresponding methods in
the parent class? For example, you might create a class called Fruit that contains methods such as
peel() , slice() , and eat() . This works for most fruit; however, grapes, for example, don ’ t need to be
peeled or sliced. So you might want your Grape object to behave somewhat differently to the generic
Fruit object if you try to peel or slice it.
PHP, like most object - oriented languages, lets you solve such problems by overriding a parent class ’ s
method in the child class. To do this, simply create a method with the same name in the child class. Then,
when that method name is called for an object of the child class, the child class ’ s method is run instead of
the parent class ’ s method:
class ParentClass {
public function someMethod() {
// (do stuff here)
}
}
class ChildClass extends ParentClass {
public function someMethod() {
// This method is called instead for ChildClass objects
}
}
196
9/21/09 9:03:41 AM
c08.indd 196 9/21/09 9:03:41 AM
c08.indd 196