Login |  Register 
Your PHP skills tool showed me were I needed to improve and how to do it!
Tom
 

Interfaces

PHP allows Interfaces to be defined much in the same way as languages such as Java and C#.

An interface is a contract that the implementing class must follow. Therefore in order for a constant or function of a interface to be seen by other classes all constants or functions must be made public.

One of the main reason interfaces are used is that it stops the problem of multiple inheritance. In multiple inheritance if a class extends two classes with the same method it won't know which to inherit from.

By using interfaces PHP allows multiple interfaces but not multiple inheritance. If a class implements two interfaces with the same method it will throw an error.

A function in a interface isn't actually implemented instead it is a contract, so the implementing class must have a function of the same signature with the same number of parameters.

Unlike some other languages PHP allows you to put constants in a interface which can be a very useful way of sharing constants between classes.

Interfaces are defined as below.

interface IPage
{
 public function setHtml($html);
 public function getHtml();
}
This can be implemented by a class as shown.
class StartPage implements IPage
{
 private $html = '';

 public function setHtml($html)
 {
  $this->$html = $html;
 }

 public function getHtml()
 {
  return $html;
 }
}
If you don't implement a function that was declared in a interface then the PHP interpreter will error. A interface can also extend other interfaces as shown below.
interface IPage
{
 public function setHtml($html);
 public function getHtml();
}

interface IWebPage extends IPage
{
 const TitleStart = "Website name - ";
}
So now a class implementing IWebPage will now have to implement everything from IWebPage and IPage.

No comments have been provided.
security image
Written by Dominic Skinner
Last Updated: 2011-10-25 16:00:38