Interface or an Abstract Class: which one to use?


Question

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?

1
306
5/24/2018 4:11:53 PM

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.

440
5/24/2018 4:08:41 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon