What is the difference between an abstract class and an interface in PHP?
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 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