Inheriting from an existing class is a very powerful tool in the Object Oriented programmer’s arsenal. However, it’s not always the appropriate one to use, because PHP doesn’t allow a class to have more than one parent class. For this reason PHP allows multiple inheritance, but only for interfaces.
An interface acts like a skeleton, and the implementing class provides the body. Although a class can have only one parent class, it can implement any number of interfaces.
In PHP, an interface is created like so:
{
CONST 1;
...
CONST N;
function methodName1();
...
function methodNameN();
}
All methods must be implemented, or the implementing class must be declared abstract.
The following is the general syntax for implementing the preceding interface:
{
function methodName1()
{
/* methodName1() implementation */
}
....
function methodNameN()
{
/* methodName1() implementation */
}
}
When should you use an interface instead of an abstract class, and vice versa? This can be quite confusing and is often a matter of considerable debate. However, there are a few factors that can help you formulate a decision in this regard:
• If you intend to create a model that will be assumed by a number of closely related objects, use an
abstract class. If you intend to create functionality that will subsequently be embraced by a number of
unrelated objects, use an interface.
• If your object must inherit behavior from a number of sources, use an interface. PHP classes can inherit
multiple interfaces but cannot extend multiple abstract classes.
• If you know that all classes will share a common behavior implementation, use an abstract class and
implement the behavior there. You cannot implement behavior in an interface.
- 771 reads













Post new comment