Implementing Interfaces
Use the implements keyword after the class name. The class must implement every method declared in the interface with matching signatures.
Use the implements keyword after the class name. The class must implement every method declared in the interface with matching signatures.
<?php
interface Serializable {
public function serialize(): string;
public function unserialize(string $data): void;
}
class User implements Serializable {
public function __construct(
private string $name,
private string $email
) {}
public function serialize(): string {
return json_encode(["name" => $this->name, "email" => $this->email]);
}
public function unserialize(string $data): void {
$obj = json_decode($data, true);
$this->name = $obj["name"];
$this->email = $obj["email"];
}
}
PHP 8 allows covariant return types in interface implementations — the implementing method can return a more specific type.