Last updated on March 24, 2023
The interface allows you to declare public methods that a class should implement. It means, when you implement an Interface into a class then it has to implement all the methods that are declared in the Interface. A class can implement multiple interfaces which is helpful behavior when you want a class to follow multiple contracts.
Sometimes, students mix the concept of Interfaces and abstract classes, however, there is a difference. One of the main differences is that a concrete class can’t extend multiple abstract classes but a subclass can implement multiple interfaces.
Syntax
interface InterfaceName {
public function methodName1();
public function methodName2($param1, $param1);
}
Rules for Implementing an Interface
Usage
Let’s create a Vehicle interface and declare methods that a vehicle needs. In the below example, we create three methods that possibly all kinds of vehicles need.
interface Vehicle
{
public function color($color);
public function tyre($count);
public function gear($totalGear);
}
To use the above interface, create a car class with the name Ferrari and implement the Vehicle interface. Once you implement the interface then the Ferrari class must have to add all the methods that are declared in the Vehicle interface.
Class Ferrari implements Vehicle{
public function color($color){
return $color;
}
public function tyre($count){
return $count;
}
public function gear($totalGear){
return $totalGear;
}
}
$ferrari = new Ferrari();
echo $ferrari->color("red");
// Output: red
echo $ferrari->tyre(4);
// Output: 4
echo $ferrari->gear(5);
// Output: 5