← Back to PHP Course | Chapter 8: OOP | Lesson 8 of 14

PHP Interfaces

What is an Interface?

An interface defines a contract of method signatures that any implementing class must provide, without specifying any implementation details itself — it says what a class must do, not how.

Example: What is an Interface?

php
<?php
interface Shape {
    function area();
}
class Circle implements Shape {
    function area() {
        return 3.14 * 5 * 5;
    }
}
$c = new Circle();
echo $c->area();
?>

Implementing Interfaces

A class agrees to an interface's contract using the implements keyword, and PHP will produce a fatal error at runtime if the class fails to define every method the interface requires.

Example: Implementing Interfaces

php
<?php
interface Shape {
    function area();
}
class Square implements Shape {
    function area() {
        return 9;
    }
}
$sq = new Square();
echo $sq->area();
?>

Multiple Interfaces

Unlike classes, PHP lets a single class implement multiple interfaces at once, which is how PHP achieves the flexibility of multiple inheritance without the ambiguity problems that true multiple class inheritance would create.

Example: Multiple Interfaces

php
<?php
interface Swims {
    function swim();
}
interface Flies {
    function fly();
}
class Duck implements Swims, Flies {
    function swim() { echo "Swimming\n"; }
    function fly() { echo "Flying\n"; }
}
$duck = new Duck();
$duck->swim();
$duck->fly();
?>

Interface Inheritance

Interfaces are especially valuable for decoupling code: a function that accepts a Countable interface, for instance, can work with any object that implements count() correctly, regardless of what concrete class it actually is.

Example: Interface Inheritance

php
<?php
class Cart implements Countable {
    private $items = ["a", "b", "c"];
    function count() {
        return count($this->items);
    }
}
$cart = new Cart();
echo count($cart);
?>

Interfaces vs. Abstract Classes

PHP itself ships with several built-in interfaces like Iterator, ArrayAccess, and Countable that let your own custom objects behave like native arrays in foreach loops or with functions like count().

Example: Interfaces vs. Abstract Classes

php
<?php
class Playlist implements Iterator {
    private $songs = ["Song A", "Song B"];
    private $position = 0;
    function current() { return $this->songs[$this->position]; }
    function key() { return $this->position; }
    function next() { $this->position++; }
    function rewind() { $this->position = 0; }
    function valid() { return isset($this->songs[$this->position]); }
}
foreach (new Playlist() as $song) {
    echo $song . "\n";
}
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.