Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^8) CHAPTER 1 ■ ABSTRACT CLASSES, INTERFACES, AND PROGRAMMING BY CONTRACT
Listing 1-5. Using a Class Without Implementing a Required Method
interface ISpeedInfo {
function getMaximumSpeed();
}
class Car {
//Any base class methods
}
class FastCar extends Car implements ISpeedInfo {
function getMaximumSpeed() {
return 150;
}
}
class BadCar extends Car{}
$a = new BadCar();
echo $a->getMaximumSpeed();
The code in Listing 1-5 will generate the following error:
Fatal error: Call to undefined method BadCar::getMaximumSpeed()
This is because BadCar does not implement ISpeedInfo, and Car does not check for the
interface before calling getMaximumSpeed(). This error condition can be detected by using the
instanceof operator, as described in the next section.
The instanceof Operator
The instanceof operator is a PHP comparison operator. It takes parameters on the left and right,
and returns a Boolean value. This operator is used to determine if an instance of an object is of
a specific type, inherits from a type, or implements a specific interface.
■Note The word type refers to the runtime definition of a specific class. A type is created any time a class
or interface definition is parsed by PHP.
For example, to avoid the error shown in the previous section, generated by Listing 1-5,
you can use instanceof to determine if the inheritor of Car implements ISpeedInfo, as shown
in Listing 1-6.
McArthur_819-9C01.fm Page 8 Tuesday, December 18, 2007 7:38 AM

Free download pdf