What is the difference between abstract class and interface in PHP?

What is the difference between abstract class and interface in PHP?

What is the difference between abstract class and interface in PHP?

Question

What is the difference between an abstract class and an interface in PHP?

Answer

Abstract Class

  • Can have both abstract (unimplemented) and concrete (implemented) methods
  • Can have properties, constructor, and constants
  • A class can extend only one abstract class
  • Use when classes share common implementation
abstract class Shape
{
    public function __construct(protected string $color) {}

    abstract public function area(): float; // must be implemented

    public function describe(): string      // shared implementation
    {
        return "A {$this->color} shape with area " . $this->area();
    }
}

class Circle extends Shape
{
    public function __construct(string $color, private float $radius)
    {
        parent::__construct($color);
    }

    public function area(): float
    {
        return M_PI * $this->radius ** 2;
    }
}

Interface

  • Only method signatures — no implementation (except default methods in some languages; not PHP)
  • No properties (only constants)
  • A class can implement multiple interfaces
  • Use to define a contract that unrelated classes can all fulfil
interface Serializable
{
    public function serialize(): string;
    public function unserialize(string $data): void;
}

interface Loggable
{
    public function toLog(): array;
}

class Order implements Serializable, Loggable
{
    public function serialize(): string { return json_encode($this); }
    public function unserialize(string $data): void { /* ... */ }
    public function toLog(): array { return ['id' => $this->id]; }
}
All Comments