Skip to content
PHP Logo

When should abstract classes be used over interfaces in PHP?

Abstract classes should be used over interfaces in PHP when you want to provide some common functionality or default implementations for a group of classes that share a common set of methods. Abstract classes can have both abstract and non-abstract methods, allowing you to define some methods that must be implemented by subclasses while providing default implementations for others. This can help reduce code duplication and enforce a consistent structure among related classes.

php
<?php
abstract class Shape {
    abstract public function calculateArea();
    
    public function printDescription() {
        echo "This is a shape.";
    }
}

class Circle extends Shape {
    private $radius;
    
    public function __construct($radius) {
        $this->radius = $radius;
    }
    
    public function calculateArea() {
        return pi() * pow($this->radius, 2);
    }
}

$circle = new Circle(5);
echo $circle->calculateArea(); // Output: 78.54
$circle->printDescription(); // Output: This is a shape.
?>