PHP Interfaces: What is, How to use and Implement PHP?

Here we are going to talk about PHP Interfaces. This article will answer What are interfaces, and how to implement them in PHP.

What are PHP Interfaces?

Interfaces work very similarly to abstract classes.

Both Interfaces and abstract classes work like the blueprint for a child class.

But in the case of the PHP interface, we do not define any properties and as for methods, all methods here are abstract only.

A child class derived from the interface can also at the same time derive properties ad methods from any other class.

We can also create objects for an interface.

While for class we use the keyword extends to get inherit from a parent class, for interface we have to use implement.

Here is the syntax to create the interface and functions inside it-

interface InterfaceName{
    function someMethod();
}

And here is how we can inherit from interface to a class-

class MyClassName implements InterfaceName{
    function someMethod(){
        //code to run
    }
}

We can implement multiple interfaces or even interface with another class to a child class if we want.

Difference between Interfaces vs. Abstract Classes

While both Abstract classes and interfaces work in a similar fashion, there are considerably a lot of differences between both two-

  • We can have properties in the Abstract Class but the same is not true for Interfaces.
  • We can define abstract class methods as either Public or Protected but All Interfaces methods must be public only.
  • Since all methods inside the interface are abstract we don’t have to use the ‘abstract’ keyword while adding abstract methods.
  • A child class can inherit from an interface at the same time inheriting from a class.

How to Implement & Use PHP Interfaces?

We can define the interface as the blueprint for the classes we will create next.

Here we can create functions but can’t implement them and to implement them we need a class.

To implement an Interface or Interfaces if that matters in PHP we use the Implements keyword.

Here is an example of a PHP Interface:

interface Phone{
    public function makeCall();
}

And this is how we can implement this interface-

class Samsung implements Phone {
    public function makeCall(){
        echo "Connecting the Call";
    }
}

and to create objects from this class-

$phone = new Samsung();
$phone->makeCall();

Some important points about Interfaces

  • We can not add properties in Interfaces in PHP.
  • We can’t create an object of interfaces.
  • A derived class can implement multiple Interfaces along with the parent class.
  • Unlike Inheriting from class, for the interface, we use the Implements keyword.
  • All functions inside the interface must be public. We can’t create Protected or Private methods inside an Interface.
  • Parameter of Interface methods inside child class must be the same as we defined in the Interface.