</>
Skip to content
PHP lessons (38/49)

PHP — Interfaces

Basic interface

<?php
interface Drawable {
    public function draw(): string;
}

class Circle implements Drawable {
    public function draw(): string {
        return "Drawing circle";
    }
}

$circle = new Circle();
echo $circle->draw(); // Drawing circle
?>

Multiple interfaces

<?php
interface Printable {
    public function print(): string;
}

interface Loggable {
    public function log(): string;
}

class Document implements Printable, Loggable {
    public function print(): string {
        return "Printing document";
    }

    public function log(): string {
        return "Logging document";
    }
}
?>

Interface constants

<?php
interface Config {
    const MAX_RETRIES = 3;
    const TIMEOUT = 30;
}

echo Config::MAX_RETRIES; // 3
?>

Interface inheritance

<?php
interface Loggable {
    public function log(): string;
}

interface AuditLoggable extends Loggable {
    public function audit(): string;
}
?>

Type hints with interfaces

<?php
interface Repository {
    public function find(int $id): array;
    public function save(array $data): bool;
}

class UserRepository implements Repository {
    public function find(int $id): array {
        return ['id' => $id, 'name' => 'Alice'];
    }

    public function save(array $data): bool {
        return true;
    }
}

function process(Repository $repo): void {
    $user = $repo->find(1);
    echo $user['name'];
}

$repo = new UserRepository();
process($repo);
?>

Mini Practice

Write PHP code that:

  1. Defines an interface with methods
  2. Implements multiple interfaces
  3. Uses an interface for type hints
  4. Creates interface constants

Up Next

In the next lesson, you'll learn about Traits — code reuse in PHP.

Related Topics

Frequently Asked Questions about Interfaces

What is Interfaces in PHP?

Interfaces is a fundamental concept in PHP. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Interfaces?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Interfaces.

Why is Interfaces important in PHP?

Interfaces is essential for PHP development. Understanding this concept will help you write better code and solve real-world problems more effectively.