Interface or an Abstract Class: which one to use?
Please explain when I should use a PHP interface
and when I should use an abstract class
?
How I can change my abstract class
in to an interface
?
Use an interface when you want to force developers working in your system (yourself included) to implement a set number of methods on the classes they'll be building.
Use an abstract class when you want to force developers working in your system (yourself included) to implement a set numbers of methods and you want to provide some base methods that will help them develop their child classes.
Another thing to keep in mind is client classes can only extend one abstract class, whereas they can implement multiple interfaces. So, if you're defining your behavior contracts in abstract classes, that means each child class may only conform to a single contract. Sometimes this a good thing, when you want to force your user-programmers along a particular path. Other times it would be bad. Imagine if PHP's Countable and Iterator interfaces were abstract classes instead of interfaces.
One approach that's common when you're uncertain which way to go (as mentioned by cletus below) is to create an interface, and then have your abstract class implement that interface.
The differences between an Abstract Class
and an Interface
:
Abstract Classes
An abstract class can provide some functionality and leave the rest for derived class.
The derived class may or may not override the concrete functions defined in the base class.
A child class extended from an abstract class should logically be related.
Interface
An interface cannot contain any functionality. It only contains definitions of the methods.
The derived class MUST provide code for all the methods defined in the interface.
Completely different and non-related classes can be logically grouped together using an interface.