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
Feature | Abstract Class | Interface |
---|---|---|
Method implementation | Can have both | Cannot (only declarations) |
Properties | Yes | No (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.
Comments are closed.