An interface defines a contract — method signatures a class must implement. A class can implement multiple interfaces.
interface Drawable {
public function draw(): string;
}
interface Serializable {
public function serialize(): string;
public function unserialize(string $data): void;
}
class Circle implements Drawable, Serializable {
public function __construct(private float $radius) {}
public function draw(): string {
return "Drawing circle r={$this->radius}";
}
public function serialize(): string {
return json_encode(["radius" => $this->radius]);
}
public function unserialize(string $data): void {
$this->radius = json_decode($data, true)["radius"];
}
}
$c = new Circle(5);
echo $c->draw(); // Drawing circle r=5
echo $c->serialize(); // {"radius":5}
interface HttpStatus {
const OK = 200;
const NOT_FOUND = 404;
const ERROR = 500;
}
echo HttpStatus::OK; // 200
function render(Drawable $shape): void {
echo $shape->draw();
}
// Accepts any class that implements Drawable
render(new Circle(3));
render(new Rectangle(5, 2));