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
<?phpinterface Interface_Name{public function FunctionName();}?>
The keyword implement allows linking the interface with its class.
Code example
<?phpinterface 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 movementforeach($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.