Understand the concept of Interface in PHP

easy solution web : OOPS in PHP

What is Interface?

An Interface contains methods without body i.e {}. Means, there we get only the declaration of the function, not the definition of the function.

A class which uses interface have to implement all of its methods declared in the interface.

Interface restricts the user to define all the method declared in the Interface in a class, which uses the interface.

How can we define an Interface?

In PHP we can define an Interface using interface keyword before the interface name as we defined below

interface MyFirstInterface{
// required code

Interface can have only Abstract Methods and Constant Variables

interface MyFirstInterface{
 const CONSTANT1 = 25; // contant variable
const CONSTANT2 = 50; // constant variable
public function method1();   // Abstract Method

How can we use Interface?

The interface can be used by the class using implements keyword.

public class MyClass implements MyFirstInterface{
   public function method1(){
// body of method1
public class MyClass implements MyFirstInterface, MySecondInterface{  
public function method1(){ 
// body of method1
// MyFirstInterface and MySecondInterface are interface here.

This how we can use multiple interfaces at once with a Class.

The interface can be used by another interface using extends keyword.

public interface MySecondInterface implements MyFirstInterface{   
        public function method2(); // abstract method;

Why Should we use Interface?

When you want some user who uses your code, should implement some method according to their need which will be customizable by the user. And you want user must implement specific methods. which will be needed by your code.

In these case, you need to define Interface which will restrict the user to implement these methods.

For example:

You are creating Article Publishing Workflow. So to restrict the user to implement compulsory methods in their ArticleWorkflow Class you will need to create an interface.

interface Workflow{
public function draft();
public function sendForReview();
public function sendForPublished();

This workflow can be used in Article Publishing Class or Image Publishing Class or Video Publishing Class etc. So Whenever you need to create a workflow you just need to implement this interface only, then this interface will decide the what method should be implemented while creating a workflow class. So by defining the workflow interface you just created a standard process to introduce a New Workflow in the system.

I hope you found this post useful and Happy Learning.