Interfaces in PHP

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

Post Reply
mudgil.gaurav
Forum Newbie
Posts: 17
Joined: Wed Oct 08, 2008 4:39 am

Interfaces in PHP

Post by mudgil.gaurav »

Hi All,

I am very keen to know the basic advantage of Interfaces over abstract classes.Because we can achive the same behaviour from
abstract class as we can do from interfaces i.e we can declare the function in abstract class same we as in interfaces.Abstract class
also gives the error when child class do not implement all abstract methods like interfaces.

Offcourse we can do the multiple inheritance by implementing multiple interfaces.

Apart from this what are the core benifits a interface provies than a abstract class.

Any suggestion or comments would be greatly appriciated.

Thanks
Gaurav
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: Interfaces in PHP

Post by Benjamin »

:arrow: Moved to PHP - Theory and Design
User avatar
PHPHorizons
Forum Contributor
Posts: 175
Joined: Mon Sep 14, 2009 11:38 pm

Re: Interfaces in PHP

Post by PHPHorizons »

Hello Gaurav,
Gaurav wrote:Off course we can do the multiple inheritance by implementing multiple interfaces.
Well that's not really true because an interface doesn't have any functionality. So by implementing an interface (not including built in interfaces), your class will gain no functionality. There is one big exception to that, which is that some built in interfaces do have some "magic" functionality, but you cannot do that with your own interfaces. Nor can you extend a built in interface to give it any more functionality. I.e., you can implement it, but you cannot extend it.

So now that we have moved away from thinking of interfaces as being inherited towards interfaces being implemented, there are some differences from abstract classes besides the fact that multiple interfaces can be implemented whilst only one abstract class can be inherited.

The biggest difference is that (again, not including built in interfaces) there is no functionality built into an interface. Therefore, when you implement an interface, you must implement all methods with the signatures provided. In an abstract class, there can be fully qualified methods that do add functionality to your class that inherits from it.

I'm not sure how php handles this, but in other languages that are strictly typed, a class that implements an interface will then be accepted in places where that interface is the type required. For instance, suppose I have a class called foo that implements bar. If I have a function with a parameter typed as bar, my foo object will be accepted because it implements bar. Therefore, a class can be made to fit multiple types by using interfaces. Now php does allow parameters of functions to by typed to a class name. I'm not sure if interface names can be used. I never tried it... If so, that would be one more difference.

The biggest thing though is that abstract classes do not necessarily say anything to the outside world about your class, but an interface does. I.e., how does one interface with a toaster? It would have a lever to lower the toast, a turning knob to set how dark the toast should be toasted, and a button to release the toast early. Every toaster that implements the IToaster interface has those features. It tells any user of the Toaster object how to publicly interact with it. An abstract class is not solely designed to provide an interface to a thing. It is a common generic platform for more specific classes that fall into a similar group. I may have an abstract toaster class called abstract_toaster which has a method named getTemp which is used by the execute() method to know when the toast is done. Now all toasters might measure the same temperature and thus getTemp may be implemented in the abstract class, but execute() is probably going to be abstract since many toasters operate differently. execute() may be called by a method from the IToaster interface called leverActuated() which will detect when the level is moved into the operating position and then calls the execute() method.

Cheers
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Interfaces in PHP

Post by Christopher »

mudgil.gaurav wrote:I am very keen to know the basic advantage of Interfaces over abstract classes.
There is no "advantage" to either interfaces or abstract classes -- they have different purposes. It is like asking what is the advantage of if() over a for() loop. Interfaces only define the interface and PHP will enforce it. Abstract classes allow you to create base classes that must be extended and additional implementation added. Both are useful.
(#10850)
josh
DevNet Master
Posts: 4872
Joined: Wed Feb 11, 2004 3:23 pm
Location: Palm beach, Florida

Re: Interfaces in PHP

Post by josh »

A class can implement a lot of interfaces, but only can inherit one abstract class
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Interfaces in PHP

Post by Weirdan »

Now php does allow parameters of functions to by typed to a class name. I'm not sure if interface names can be used. I never tried it...
PHP accepts interface names in type hints and enforces it, just like if you used concrete class there.
User avatar
MindOverBody
Forum Commoner
Posts: 96
Joined: Fri Aug 06, 2010 9:01 pm
Location: Osijek, Croatia

Re: Interfaces in PHP

Post by MindOverBody »

I struggled so long with interfaces and asked myself are interfaces really necessary in my code, do my classes need to implement interfaces, so one day i started to develope some module system. Interfaces came like a glove, when i needed to tell what methods future module classes should have. With interface you can tell to some other fancy developer what methods his extended class must have. For example class hook method.
webaddict
Forum Commoner
Posts: 60
Joined: Wed Mar 14, 2007 6:55 am
Location: The Netherlands

Re: Interfaces in PHP

Post by webaddict »

Hi.

This has actually been a question I've been asked a thousand times already in the past, and I've always found it a hard one to answer. Like Christopher already said, there is a huge difference and they are not alike, but it seems there is no clear consensus on when to use which. For me, an abstract class indeed gives you some base implementation that will be shared among all children of the abstract class, which means you don't have to copy the overlapping pieces of code. It's just inheritance, but you can't instantiate the abstract base class.

However, for me, there is a bigger difference. In my view, having an abstract class will not only give all it's children a piece of shared implementation, but also one concrete type. That is to say, if you have a TemplateParser class, all of it's children will naturally also have the type TemplateParser (even if the concrete implementation uses Smarty). You have an abstract class, you have concrete implementations. The concrete implementations will always be the type of the parent class.

Interfaces don't offer the shared implementation amongst it's implementers, well known fact. It *does* however denote which behaviour the implementer implements, without dictating it's type. If we take the Serialisable interface as an example, a TemplateParser can be serialisable (Huh? Well, it can!), and so can a User Object, a Post object, and every other object you think might be useful to serialise. All it says is that they are able to serialise themselves, it doesn't say which type of object it is per se.

So, if you were to ask me, and you sort of did -- well, not me, but the whole forum, which includes me -- it's all about behaviour vs. type. I'd be happy to know if there are people that disagree with me, I know for example that the Zend Framework uses interfaces to dictate behaviour *and* type at the same time [1], where an abstract class would've been a better fit in my book.

Ideas?

[1] http://framework.zend.com/apidoc/1.10/Z ... rface.html

EDIT: Oh, arborint is now Christopher. Didn't notice before. :)
User avatar
pedrotuga
Forum Contributor
Posts: 249
Joined: Tue Dec 13, 2005 11:08 pm

Re: Interfaces in PHP

Post by pedrotuga »

I asked this question to several people in the past and the answers always ended up resourcing to words like "must", "force", etc. to explain the use value of interfaces, which is kind of silly because it assumes that you have some kind of magical control over what can be done with code you distribute.

Personally, I am as skeptical as mudgil. If I use classes instead of interfaces, and tell those who extend them which methods must be implemented etc. then they classes kind of same the same purpose than interfaces, except multiple inheritance.

That is exactly what python programmers do. In general, python offers access to everything and it's up to the programmer not to break whatever he/she is using. Kind of a gentlemen agreement rather than a rule.

Java programmers, on the other hand tend to use interfaces all over the place. I suppose A dummy class with all public methods containing 'return null;' would work as well as an interface in many cases.

So i would say that apart from multiple inheritance, interfaces are kind of syntax sugar for classes serving a specific purpose. Unarguably, that syntax sugar have come a long way.
josh
DevNet Master
Posts: 4872
Joined: Wed Feb 11, 2004 3:23 pm
Location: Palm beach, Florida

Re: Interfaces in PHP

Post by josh »

pedrotuga wrote:I asked this question to several people in the past and the answers always ended up resourcing to words like "must", "force", etc. to explain the use value of interfaces, which is kind of silly because it assumes that you have some kind of magical control over what can be done with code you distribute.
Not it isn't and no it doesn't.
classes kind of same the same purpose than interfaces, except multiple inheritance.
Wrong. My microwave is like my phone in that they both have number pads. So do they serve the same purpose? Programmers didn't create interfaces just to confuse other programmers. They serve a purpose. A class specifies an implementation. An interface specifies an interface. They are polar opposites, not "kinda" the same thing. I don't even call it inheritance because you're not inheriting anything. Its an interface. It gets implemented, not inherited.

Sorry but try reading a thread before posting in it. PHPHorizons, Christopher and I are 100% correct.
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Re: Interfaces in PHP

Post by alex.barylski »

A class specifies an implementation. An interface specifies an interface. They are polar opposites, not "kinda" the same thing
Polar opposites? I disagree. A class, like an interface provides an interface, only unlike a interface it *can* also provide an implementation. They are very much a like, IMO, hence the confusion.

The problem with PHP is it's not very common you need to implement more than once interface, and in many cases an abstract class will suffice. For example in a Windowèd environement where you have a huge and complex hierarchy of pre-existing classes, interfaces are more useful. If a application developer anticipates letting you being able to drop in new èditor controls, they know in advance these controls are composites of many different subclasses. For instance drag and drop, text selection, data interaction, rendering, search and replace, the list could go on an on.

In this case, the IDE core-developer might deliver a bare-bones template implementing several interfaces, not classes, for two reasons:

1. To avoid the diamond of death (http://en.wikipedia.org/wiki/Diamond_problem) disuading developers from using MI.
2. To help promote a light weight implementation. MI can result in massive code bloat.

What the interface does, from this point, is something like:

Code: Select all

abstract class AbstractEditor implements IDragDrop, ITextSelection, IDataBuffer, ITextRender{
  
}
Now, instead of spoon feeding advanced developers by providing entire implementations, you allow clients to build exactly what they want according to your specification, in this case, an interface.

If you fail to implement all required methods, when you compile and run your editor, chances are it will not work as expected and may even crash or cause exceptions. So again, in this case, an interface serves as documentation as to what needs to be implemented. Very similar to how unit tests demonstrate how components and dependencies interact.

Cheers,
Alex
josh
DevNet Master
Posts: 4872
Joined: Wed Feb 11, 2004 3:23 pm
Location: Palm beach, Florida

Re: Interfaces in PHP

Post by josh »

PCSpectra wrote:Polar opposites? I disagree. A class, like an interface provides an interface, only unlike a interface it *can* also provide an implementation. They are very much a like, IMO, hence the confusion.
The confusion is created because you're referring to a classe's signature as its interface. But when I say interface I'm not talking bout the signature of a class. I'm talking about a programming language feature called 'the interface'. I'm using terms from the manual and you're using ones that you see fit. One is an "is a" relationship, the other is a "can do" relationship.

Can you point to somewhere in PHP the manual they show a class and describe it as/as having an interface?
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Re: Interfaces in PHP

Post by alex.barylski »

But when I say interface I'm not talking bout the signature of a class. I'm talking about a programming language feature called 'the interface'.
Do you mind explaining to me the difference? If you change the signature, you change the interface, try it:

Code: Select all

interface MyInterface{
  public function doSomething($boink);
}

class MyClass implements MyInterface{
  public function doSomething($boink, $bonk)
  {

  }
}
PHP Fatal error: Declaration of MyClass::doSomething() must be compatible with that of MyInterface::doSomething()
You cannot change one, without changing the other. The method signature is directly dictated by what is specified in the interface.

An interface encompasses one or more methods. I suppose if you look at an interface as a whole as opposed to a single method, that would cause some confusion in discussion. That being said, you said "classes" are polar opposites of "interfaces" and a class, like an interface encompasses one or more methods. In both cases the "interface" (whether the abstract POV or concrete in case of a class) are much the same, not polar opposites, IMO.

Cheers,
Alex
josh
DevNet Master
Posts: 4872
Joined: Wed Feb 11, 2004 3:23 pm
Location: Palm beach, Florida

Re: Interfaces in PHP

Post by josh »

PCSpectra wrote:Do you mind explaining to me the difference?
..... I thought I just did. Apparently not, I guess.
If you change the signature, you change the interface
If you change the interface, you change the signature. Sure. Not always the other way around. This doesn't change the fact they are distinct concepts, just because they correlate in this way. Adding a method to a class changes the classes's signature. It does not change the interface unless I change a method that is declared by the interface.
PCSpectra wrote: an interface encompasses one or more methods.
From the manual: 'Object interfaces allow you to create code which specifies which methods a class must implement'. Again confusion arises from your use of non-standard terminology. "Encompasses" - you're implying interfaces have an implementation. Beating a dead horse here.
PCSpectra wrote: you said "classes" are polar opposites of "interfaces" and a class,
In terms of their purposes, they are
In both cases the "interface" (whether the abstract POV or concrete in case of a class) are much the same, not polar opposites, IMO.
Yeah, they have some similarities in regards to implementation within the language, we established that page 1.
Post Reply