Introduction to PHP - Understanding Interface Part 1

Guest Posts Paolo Nikko Nuñal

In our previous tutorial we discussed about how Abstract classes work, in this tutorial we are going further on how interfaces work and their difference between abstract classes. Object Oriented Programming can be quite hard, but once you have mastered it, creating programs will be a breeze and your system flow will be clean and easy to understand. Interface are like contracts that you need to implement on your class. This is especially useful if you are working on a large project and you want a systematic or uniform approach when dealing with other programmers working on another class.

Interfaces will serve as a contract that must be followed. It does not contain any member variables but rather only functions.

To illustrate here's an example.

   interface Automobile{
      public function buildChasis();
      public function buildBodyCover();
      public function setEngine($engine);
   class Dodge implements Automobile{
    public function buildChasis(){}
    public function buildBodyCover(){}
    public function setEngine($engine){}

From the example above we have created an Interface that is named Automobile, that has three functions namely buildChasis, buildBodyCover and setEngine. Another class we have created is the Dodge class that implements the Automobile interface. Base from the example, the Dodge class implements the Automobile interface and therefore must use all the methods that is declared in the Automobile interface. That includes the signature of the methods.

In order for you to use an interface you need to use the keyword 'implements' followed by the name of the interface.