Implementing an Interface

Your rating: None

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:

interface IinterfaceName
{
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:

class className implements interfaceName
{
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.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Copy the characters (respecting upper/lower case) from the image.

Cumulus Tag Cloud

Kiran Says

SEO Architect,SEO Specialist reflect my values.

By enduring black hat methods the SEO industry is setting itself up for washout and sleepwalking into oblivion.

Jobs in India