June 4, 2025

Abstract Classes vs Interfaces in PHP

This question is frequently asked to test your understanding of object-oriented design and code structure.


🧩 Abstract Class β€” What is it?

An abstract class:

  • Cannot be instantiated directly
  • Can have defined methods and abstract methods (methods with no body)
  • Can have properties
  • Can contain constructor
  • Supports inheritance
abstract class Animal {
    protected $name;

    public function __construct($name) {
        $this->name = $name;
    }

    abstract public function makeSound();

    public function getName() {
        return $this->name;
    }
}

class Dog extends Animal {
    public function makeSound() {
        return "Bark";
    }
}

βš™οΈ Interface β€” What is it?

An interface:

  • Only contains method declarations, no implementation
  • No properties (until PHP 8.1: readonly properties)
  • A class can implement multiple interfaces
interface Logger {
    public function log($message);
}

class FileLogger implements Logger {
    public function log($message) {
        echo "Writing to file: $message";
    }
}

πŸ†š Abstract Class vs Interface β€” Key Differences

FeatureAbstract ClassInterface
Method implementationCan have bothCannot (only declarations)
PropertiesYesNo (except constants / PHP 8.1+)
Multiple inheritance❌ Noβœ… Yes (a class can implement many)
Constructorsβœ… Yes❌ No
Use caseβ€œIs-a” relationshipβ€œCan-do” capabilities

Interview Tip:

If you need shared code with structure β€” use abstract classes.
If you need to define a contract for capabilities β€” use interfaces.