Interfaces specify the methods that a class must implement, making it easy to use different classes in the same way. When multiple classes implement the same interface, it is known as “polymorphism”.
Interfaces are declared using the interface
keyword:
<?php interface InterfaceName { public function someMethod1(); public function someMethod2($name, $color); public function someMethod3() : string; } ?> |
Interfaces are similar to abstract classes, but there are key differences:
abstract
keyword.To implement an interface, a class must use the implements
keyword.
A class implementing an interface must implement all the methods defined by that interface.
<?php interface Animal { public function makeSound(); } class Cat implements Animal { public function makeSound() { echo “Meow”; } } $animal = new Cat(); $animal->makeSound(); ?> |
From the example above, let’s say we want to write software to manage a group of animals. There are actions that all animals can perform, but each animal does them in its own way.
Using interfaces, we can write code that works for all animals, even if each animal behaves differently.
<?php // Interface definition interface Animal { public function makeSound(); } // Class definitions class Cat implements Animal { public function makeSound() { echo ” Meow “; } } class Dog implements Animal { public function makeSound() { echo ” Bark “; } } class Mouse implements Animal { public function makeSound() { echo ” Squeak “; } } // Create a list of animals $cat = new Cat(); $dog = new Dog(); $mouse = new Mouse(); $animals = array($cat, $dog, $mouse); // Tell the animals to make a sound foreach($animals as $animal) { $animal->makeSound(); } ?> |
Cat, Dog, and Mouse are all classes that implement the Animal interface, which means they can all make a sound using the makeSound() method. This allows us to loop through all the animals and instruct them to make a sound, even if we don’t know the type of animal each one is.
Since the interface does not dictate how the method should be implemented, each animal can make a sound in its own unique way.