SyntaxStudy
Sign Up
PHP Implementing an Interface
PHP Intermediate 5 min read

Implementing an Interface

Implementing Interfaces

Use the implements keyword after the class name. The class must implement every method declared in the interface with matching signatures.

Example
<?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"];
    }
}
Pro Tip

PHP 8 allows covariant return types in interface implementations — the implementing method can return a more specific type.