Interfaces And Abstract Classes
Let’s talk about the most popular question in programmers job interview:
What is the difference between interface and abstract class?
Ok, the simple answer is that abstract class can contain some code, but interface contains only function or fields definitions. As for PHP, interface can define only functions.
Another obvious thing is that this obvious answer is not interesting at all. The real question sounds like this one:
What do you mean when you declare
class Concrete extends Abstract? And what do you mean when you declare
class Concrete implements Interface?
Let’s try to answer this question.
When some class extends the other one, it tells that it actually is this class with some small changes. You can even not mention the difference.
When some class implements an interface, it tells that it can do what defined in interface. You should not bother yourself with how.
This difference will be illustrated be the following real-world example.
Real world example
Spouses are not relatives in terms of law in many countries. Here in Russia we have a law, defining full list of relationship types, which are close enough to call these people relatives. As far as I know, analogue of this document exists in many other countries.
Nevertheless, Spouse can behave like a relative in cases of emergency and pretend on inheritance. As everybody knows, those are basic functions for relatives.
Pay a bit of attention to the fact that class
Spouse does not extend
AbstractRelative, it just implements
Choice: Inheritance or Implementation?
There is only good answer: it depends. If you are sure that all concrete classes will have only common behavior, but not a code, you obviously should start from interfaces.
Another approach is to replace
acts as and try the definitions on taste :)
Spouse is Relative? definitively no. Spouse acts as Relative? Yes.
Yet another approach is to start from abstract classes and extract interface when you need a class that is not abstract one.