Pro PHP- Patterns, Frameworks, Testing and More

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

any methods that are declared abstract in the base class but that are not implemented in the
inheriting class. You should implement the methods instead of marking the class abstract,
because marking it abstract would prevent the class’s instantiation and just push the error
further downstream.
You must implement all methods in an interface such that a complete class can be formed
and such that other classes may be allowed to depend on the existence of all the methods
defined in the interface. Failing to implement even one interface method defeats the purpose
of defining a common interface and thus is not permitted.
As noted, one benefit of interfaces over abstract classes is that you may use more than one
interface per class. When you wish to implement two or more interfaces in a class, you separate
them with commas. For example if you had an array style object that you wanted to be both
iterable and countable, you might define a class like this:

class MyArrayLikeObject implements Iterator, Countable {}

It is entirely possible to achieve the same operation as abstract classes using interfaces.
Usually, you will use an abstract class where there is a logical hierarchy between the child and
parent classes. You will generally use an interface where there is a specific interaction you wish
to support between two or more objects that are dissimilar enough that an abstract class would
not make sense.
For example, suppose you want to convert the code in Listings 1-1 through 1-3 from their
abstract form. First, create an interface called ISpeedInfo:

interface ISpeedInfo {
function getMaximumSpeed();
}

This interface defines the getMaximumSpeed() method, replacing the abstract method in
Car.
Next, remove the abstract method from the Car class. Then change the declaration of
FastCar to include implements ISpeedInfo, as follows:

class Car {
//Any base class methods
}

class FastCar extends Car implements ISpeedInfo {
function getMaximumSpeed() {
return 150;
}
}

This code will result in nearly identical operation as the prior abstract approach. The only
important difference is that in the abstract approach, you can be assured that an implementing
class has the getMaximumSpeed() method. In the interface approach, the class Car as defined
does not necessarily know that its inheritor implements ISpeedInfo. Consider the code in
Listing 1-5.

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

Free download pdf