Page 219 - Beginning PHP 5.3
P. 219
Chapter 8: Objects
$car-> color = $color;
}
}
$car = new Car;
$garage = new Garage;
$car-> color = “blue”;
$garage-> paint( $car, “green” );
echo $car-> color; // Displays “green”
This code creates two classes: Car , with a single $color property, and Garage , with a paint()
method. This method takes a Car object and a color string, and changes the car ’ s $color property
to the string provided. You can see this in action in the code after the Garage class, which creates new
Car and Garage objects, sets the Car object ’ s color to blue, then calls the Garage object ’ s paint()
method to change the car ’ s color to green. So far so good.
However, suppose that another, somewhat naive programmer wants to use your Garage class to paint a
cat, rather than a car. They create a string variable holding the name of the cat, then try to use the
paint() method on it:
$cat = “Lucky”;
$garage = new Garage;
$garage-> paint( $cat, “red” ); // Error!
Unsurprisingly, PHP takes exception to this, generating the following warning - level error:
PHP Warning: Attempt to assign property of non-object
This is because the Garage::paint() method has attempted to change the $color property of a string,
“Lucky” , which is of course impossible. The error is really in the calling code — it shouldn ’ t have passed
a string as the first argument to Garage::paint() — but the script actually falls over inside the
paint() method. If the paint() method was quite long, or if it in turn called other methods, it could
get quite hard to track down the source of the problem.
This is where type hinting comes into play. You can use a hint to tell PHP that Garage::paint() should
expect a Car object as its first argument, and reject any other type of argument. To do this, you simply
place the class name before the argument name, as follows:
public function paint( Car $car, $color ) {
Now, if the same programmer tries to call the paint() method with a string instead of a Car object as
the first argument, PHP gives an error similar to the following:
PHP Catchable fatal error: Argument 1 passed to Garage::paint() must be an
instance of Car, string given, called in script.php on line 23 and defined in
script.php on line 9
This is much more helpful, because it lets you track down the problem to the calling code, rather than
wasting time looking inside the method for a bug.
181
9/21/09 9:03:36 AM
c08.indd 181
c08.indd 181 9/21/09 9:03:36 AM