Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I create Interfaces in PHP? [duplicate]

Tags:

php

Possible Duplicate:
What is the point of interfaces in PHP?

Why should I create Interfaces in PHP?

As I understands, interfaces are there to describe classes that implement them. The classes have to contain at least these functions. This is all fine if you're building upon someone else's work, or have to maintain a degree of compatibility. But in more simplistic cases?

I know, that for the compiled programming languages, like C++, usage of interfaces allows for an increase in compiling speed, but what about PHP? This advantage seems to disappear, since PHP is interpreted, rather than compiled.

like image 417
Janis Peisenieks Avatar asked Nov 13 '10 19:11

Janis Peisenieks


Video Answer


2 Answers

Interfaces are a way of 'emulating' multiple inheritance. A class in PHP can extend only one parent class, but can implement any number of interfaces, thus allowing you to create objects having many different types.

like image 66
Mchl Avatar answered Oct 04 '22 02:10

Mchl


Perhaps a real world example will help to illustrate this. Imagine you need to build a series of logging classes that record messages to various media such as a text file, XML or a database. Each class needs to have separate code to interact with the different types of storage of course. However if they all implement the same interface the 'public face' that they show to other code is always the same. In that way other code that uses logging objects doesn't need to know what class they are instances of or what the storage medium is. All that they need to know is that all of the logging classes, by virtue of the fact that they all implement the same interface, share a common API. This can be a very powerful way of working. You can build up a library of code that solves related problems in different ways and simply 'plug and play' these in your code.

like image 26
Jeremy Avatar answered Oct 04 '22 02:10

Jeremy