Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^6) CHAPTER 1 ■ ABSTRACT CLASSES, INTERFACES, AND PROGRAMMING BY CONTRACT
Abstract classes are not without their limitations, however. PHP supports extending from
only a single base class, so you cannot derive from two or more abstract classes. The ability to
extend from two or more base classes is commonly called multiple inheritance and is illegal by
design in PHP. The reasoning is that descending from multiple classes can cause unwanted
complexity when two or more classes define fully defined methods with the same prototype.
When you find that you want to descend from two or more abstract classes, an alternative is to
split out the base class methods and use interfaces to achieve the same goals, as described in
the next section.
Interfaces
An interface is a class-like structure that allows you to declare which methods an implementing
class must declare. For example, interfaces are often used to declare an API without defining
how it will be implemented.
While similar to an abstract class, an interface may contain only method prototypes and
must not contain any fully defined methods. This prevents the method conflicts that can arise
with abstract classes and allows you to use more than one interface for a given implementing
class. However, since you cannot define fully defined methods, if you wish to provide default
functionality for inheritors, you must also provide a non-abstract base class separately.
To declare an interface, you use the interface keyword:
interface IExampleInterface {}
■Note Many developers choose to prefix interface names with a capital I to clearly distinguish them from
classes, both in code and in generated documentation.
Instead of extending from the interface as you would an abstract class, use the implements
keyword:
class ExampleClass implements IExampleInterface {}
If you mark a class as implementing an interface and fail to implement all the interface’s
methods, you will see an error similar to this:
Fatal error: Class ExampleClass contains 1 abstract method and must therefore
be declared abstract or implement the remaining methods
(IExampleInterface::exampleMethod)
This error means that if any method in an interface is not declared, it is assumed that the
method is abstract. And since any class containing an abstract method must also be abstract,
the class must be marked as abstract to be parsed successfully. To resolve this error, implement
McArthur_819-9C01.fm Page 6 Tuesday, December 18, 2007 7:38 AM

Free download pdf