Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
CHAPTER 1 ■ ABSTRACT CLASSES, INTERFACES, AND PROGRAMMING BY CONTRACT^5

Now you have a class, FastCar, which can be instantiated. Next, you can create another
class, named Street, which will use this common functionality, as shown in Listing 1-3.

Listing 1-3. Using Abstract Common Functionality

class Street {
protected $speedLimit;
protected $cars;

public function __construct($speedLimit = 200) {
$this->cars = array(); //Initialize the variable
$this->speedLimit = $speedLimit;
}

protected function isStreetLegal($car) {
if($car->getMaximumSpeed() < $this->speedLimit) {
return true;
} else {
return false;
}
}

public function addCar($car) {
if($this->isStreetLegal($car)) {
echo 'The Car was allowed on the road.';
$this->cars[] = $car;
} else {
echo 'The Car is too fast and was not allowed on the road.';
}
}

}

The Street class includes an addCar() method, which is designed to take an instance
of a derived Car. Now you can use the Street class and pass an instance of the FastCar class
to the addCar() method, as shown in Listing 1-4. The addCar() method makes a call to the
isStreetLegal() method, which will then call the getMaximumSpeed() method defined in the
FastCar class.

Listing 1-4. Using an Abstract Class

$street = new Street();
$street->addCar(new FastCar());

Using an abstract class makes it possible to know that all Car-derived objects will imple-
ment the getMaximumSpeed() method and share common functionality. If a class inherits from
Car and does not define the method, it will result in a syntax error, and the program will not
run. This restriction allows you to guarantee compatibility at the instantiation layer, rather
than needing to later debug the code to find out why an object does not contain the method.

McArthur_819-9C01.fm Page 5 Tuesday, December 18, 2007 7:38 AM

Free download pdf