Page 217 - Beginning PHP 5.3
P. 217
Chapter 8: Objects
❑ brake() does the opposite of accelerate() — it decreases speed by 10 mph, returning true if
successful, or false if the car is stationary
❑ getSpeed() simply returns the car ’ s current speed, in mph
The script then creates an instance of the Car class — the $myCar object — and sets its public properties
to reflect a specific car (a red Volkswagen Beetle). Finally, the script displays these properties, then
runs through a couple of loops, accelerating the car to top speed then decelerating back down to zero
mph, and displaying the current speed as it goes by using the getSpeed() method.
Notice that the Car class contains a private property, $_speed . This is good OOP practice, because
you should keep an object ’ s data and behaviors private unless they absolutely need to be publicly
available. In this case, you don ’ t want outside code to be able to directly read or modify the car ’ s
speed; instead the calling code should use the three methods you created. For this reason, it makes
sense for $_speed to be private.
Incidentally, the underscore at the start of the $_speed variable name is a common coding practice
used to indicate private properties and methods. You don ’ t have to use this convention, but it can
make it easier to identify private class members at a glance.
Static Methods
PHP lets you create static methods in much the same way as static properties. To make a method static,
add the static keyword before the function keyword in the method definition:
class MyClass {
public static function staticMethod() {
// (do stuff here)
}
}
To call a static method, write the class name, followed by two colons, followed by the method name and
the arguments (if any) in parentheses:
MyClass::staticMethod();
As with static properties, static methods are useful when you want to add some functionality that ’ s
related to a class, but that doesn ’ t need to work with an actual object created from the class. Here ’ s a
simple example:
class Car {
public static function calcMpg( $miles, $gallons ) {
return ( $miles / $gallons );
}
}
echo Car::calcMpg( 168, 6 ); // Displays “28”
179
9/21/09 9:03:35 AM
c08.indd 179
c08.indd 179 9/21/09 9:03:35 AM