What are interfaces in PHP?

Overview

An interface is generally regarded as a higher level of abstraction. It allows the user to specify the public methods that a class must implement. This reduces the complexity associated with these methods.

The structure of an interface is similar to a class, but there are significant differences that cannot be overlooked. For instance, the class keyword here is replaced with the interface keyword. Moreover, only function prototypes are available in the interface.

Note: Interface declaration requires the use of the keyword interface.

Syntax

<?php
interface Interface_Name
{
public function FunctionName();
}
?>

The keyword implement allows linking the interface with its class.

Code example

<?php
interface Animal {
public function move();
}
class Lion implements Animal {
public function move() {
echo "Lion moves.";
}
}
class Dog implements Animal {
public function move() {
echo "Dog moves.";
}
}
class Cow implements Animal {
public function move() {
echo "Cow moves.";
}
}
class Horse implements Animal {
public function move() {
echo "Horse moves.";
}
}
// animals
$lion = new Lion();
$dog = new Dog();
$cow = new Cow();
$horse = new Horse();
$animals = array($lion, $dog, $cow, $horse);
// each animal's movement
foreach($animals as $animal) {
$animal->move();
echo "\n";
}
?>

Explanation

In the code above, the Lion, Dog , Cow and Horse classes implement the Animal interface. They all must implement the move() function because it is provided in the Animal interface.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources