Pro PHP- Patterns, Frameworks, Testing and More

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

Listing 1-6. Using the instanceof Operator

class Street {
protected $speedLimit;
protected $cars;

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

function isStreetLegal($car) {
if($car instanceof ISpeedInfo) {
if($car->getMaximumSpeed() < $this->speedLimit) {
return true;
} else {
return false;
}
} else {
//The extended class must implement ISpeedInfo to be street legal
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.';
}
}

}

As shown here, you use the instanceof operator on the Car instance. If it returns true, you
then know that it is safe to call any method that is defined in the interface.
Now that you’ve learned about abstract classes and interfaces, let’s talk about program-
ming by contract.

Programming by Contract
In simple terms, programming by contract is the practice of declaring an interface before writing a
class. This can be particularly useful for guaranteeing the encapsulation of your classes.
Using the programming by contract technique, you will be able to identify the capabilities
you are trying to implement before building your application, much in the same way an archi-
tect creates plans for a building before it is constructed.

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

Free download pdf