Interfaces versus Abstract classes in PHP

Interfaces and abstract classes are similar because neither one can be used directly to instantiate an object. The key difference is that an abstract class can have some fully implemented methods, whereas interfaces just have method declarations. Use abstract classes when you want to maintain the same methods in all your subclasses but have some general functionality that can be shared by the subclasses. Use interfaces when the implementations will differ across most or all the methods in subclasses.

Edited on 12th December @ 13:00 Hrs
More differences are as follows:

  • Interfaces provide a form of multiple inheritance. A class can extend only one other class.
  • Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc.
  • A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class.
  • Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast.

Similarities:

  • Neither Abstract classes or Interface can be instantiated.

Edited (again :-/ ) on 16th Dec @ 16:40 Hours IST

When to use what?

  • Use Abstract class for creating a bond between similar items like Splendor and Bullet 350 are similar entities, motor bikes, so extend them from abstract class like Bike.
  • Use interface for creating a bond between dissimilar items like Splendor and Civic are different from Bike but both are vehicles, have engine, have mileage, have wheels, consume fuel, and so many common behaviors.
  • Always try to use Abstract class or interface whenever you need to up-cast them to achieve simplicity e.g. accelerate and brake methods of bikes.

(not so) Short and (but still) sweet. 🙂

Leave a comment

Your email address will not be published. Required fields are marked *