W3docs

Interface or an Abstract Class: which one to use?

An interface defines a set of methods that a class must implement, but does not provide any implementation for those methods.

An interface defines a set of methods that a class must implement. While traditional interfaces only contained method signatures, PHP 8.1+ allows interfaces to provide default method implementations. An abstract class, on the other hand, can provide concrete implementations for its methods, in addition to defining abstract methods that derived classes must implement.

In general, use an interface when you want to specify a contract for a class to implement, especially when a class needs to implement multiple contracts. Use an abstract class when you want to provide a common implementation for some methods, but still want to allow derived classes to add their own unique behavior.

In PHP, both abstract classes and interfaces can have constants, properties, and methods. However, interface methods and properties must be public, and interfaces cannot have constructors. Abstract classes support single inheritance, while a class can implement multiple interfaces. Note that this example requires PHP 7.4+ due to typed properties and return types.

Here's an example:

Example of Interface and Abstract Class differences in PHP

<?php

interface Shape
{
  public function getArea(): float;
}

abstract class AbstractShape implements Shape
{
  protected float $width;
  protected float $height;

  public function __construct(float $width, float $height)
  {
    $this->width = $width;
    $this->height = $height;
  }

  abstract public function getArea(): float;
}

class Rectangle extends AbstractShape
{
  public function __construct(float $width, float $height)
  {
    parent::__construct($width, $height);
  }

  public function getArea(): float
  {
    return $this->width * $this->height;
  }
}

class Triangle extends AbstractShape
{
  public function __construct(float $width, float $height)
  {
    parent::__construct($width, $height);
  }

  public function getArea(): float
  {
    return 0.5 * $this->width * $this->height;
  }
}

$rectangle = new Rectangle(5, 10);
$triangle = new Triangle(5, 10);

echo "The area of the rectangle is: " . $rectangle->getArea() . "\n";
echo "The area of the triangle is: " . $triangle->getArea() . "\n";

In this example, the Shape interface defines a contract for classes that represent shapes, with a single method getArea() that returns the area of the shape. The AbstractShape class provides a common implementation for the width and height properties, as well as a constructor. It declares getArea() as an abstract method, requiring the Rectangle and Triangle classes to provide their own specific implementations.