PHP interfaces, traits, and abstract classes
PHP supports single inheritance, so a class has only one parent. An interface lists method signatures that implementing classes must provide, and a class can implement many interfaces. A trait is a reusable set of methods that is copied into a class with use. It is the way to share code between classes that are not related by inheritance.
PHP
<?php
interface Shape
{
public function area(): float;
}
trait Describes
{
public function describe(): string
{
return static::class . " with area " . number_format($this->area(), 2);
}
}
abstract class Base implements Shape
{
use Describes;
}
final class Circle extends Base
{
public function __construct(private float $radius) {}
public function area(): float
{
return M_PI * $this->radius ** 2;
}
}
final class Rect extends Base
{
public function __construct(private float $width, private float $height) {}
public function area(): float
{
return $this->width * $this->height;
}
}
foreach ([new Circle(1.5), new Rect(2, 3.5)] as $shape) {
echo $shape->describe(), "\n";
}
echo (new Circle(1)) instanceof Shape ? "a Circle is a Shape" : "not a Shape", "\n";