PHP Interfaces
In this page:
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
interface Shape {
function area();
}
class Circle implements Shape {
function area() {
return 3.14 * 5 * 5;
}
}
$c = new Circle();
echo $c->area();
?>
Login to try C/C++/Java/PHP code in the editor
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
interface Shape {
function area();
}
class Square implements Shape {
function area() {
return 9;
}
}
$sq = new Square();
echo $sq->area();
?>
Login to try C/C++/Java/PHP code in the editor
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
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();
?>
Login to try C/C++/Java/PHP code in the editor
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
class Cart implements Countable {
private $items = ["a", "b", "c"];
function count() {
return count($this->items);
}
}
$cart = new Cart();
echo count($cart);
?>
Login to try C/C++/Java/PHP code in the editor
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
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 try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: