Interfaces in PHP

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

  • In the interface, by default all methods are public, but if you put a private or protected access modifier then the class wouldn’t be able to implement and return you an error. So make sure that all declared methods in the interface are public.
  • Only implement the interface into a class when you need all the declared methods otherwise the class will return an error mentioning that all the remaining methods must be implemented.

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


Written by
I am a skilled full-stack developer with extensive experience in creating and deploying large and small-scale applications. My expertise spans front-end and back-end technologies, along with database management and server-side programming.

Share on:

Related Posts

Tags: PHP, PHP-OOP,