Why we need interface in PHP?

An interface allows unrelated classes to implement the same set of methods, regardless of their positions in the class inheritance hierarchy. An interface enables you to model multiple inheritance because a class can implement more than one interface whereas it can extend only one class.

Interfaces are 100% abstract classes – they have methods but the methods have no ‘guts’.

Interfaces cannot be instantiated – they are a construct in OOP that allows you to inject ‘qualities’ into classes .. like abstract classes.

Where an abstract class can have both empty and working/concrete methods, interface methods must all be shells – that is to say, it must be left to the class (using the interface) to flesh out the methods.

Interfaces allow you to define/create a common structure for your classes – to set a standard for objects.

Interfaces solves the problem of single inheritance – they allow you to inject ‘qualities’ from multiple sources.
Interfaces provide a flexible base/root structure that you don’t get with classes.

Interfaces are great when you have multiple coders working on a project – you can set up a loose structure for programmers to follow and let them worry about the details.


Interesting Point
A class cannot implement two interfaces that has the a same method name because it would end up with the method ambiguity.

Like classes, it is possible to establish an inheritance relationship between interfaces by using the same keyword “extends”.

Why should we use PHP interfaces?

There are several reasons that we should use interface in our PHP object-oriented programming:

By implement an interface, the caller of the object need to care only about the object’s interface, not implementations of the object’s methods. Therefore the implementations can be changed without affecting the caller of the interface.
An interface allows unrelated classes to implement the same set of methods, regardless of their positions in the class inheritance hierarchy.
An interface enables you to model multiple inheritance because a class can implement more than one interface whereas it can extend only one class.

Comments

Popular posts from this blog

Basic Terminology

Introduction To PHP

What is normalization in DBMS?