Interface in PHP with Example

Mohasin Hossain
2 min readSep 22, 2023

--

Today we going to explore what is Interface in PHP and how to use it.

Few things we need to know about Interface.

Think of an interface as a class with no behavior. Instead, it describes the terms for a particular contract.
interface as a class with no behavior only method signature
Any class that signs / implements this contract must adhere to those terms.

In PHP, an interface is a blueprint for classes. It defines a set of methods that a class must implement. Interfaces allow you to establish a contract between different classes, ensuring that they provide specific functionality. A class that implements an interface must define all the methods declared in that interface.

Let’s see some code example

interface Newsletter
{
public function subscribe($user);
}

class CampaignMonitor implements Newsletter
{
public function subscribe($email)
{
die('Subscribe from Campaign monitor');
}
}

class Drip implements Newsletter
{
public function subscribe($email)
{
die('Subscribe from Drip');
}
}

class Sendgrid implements Newsletter
{
public function subscribe($email)
{
die('Subscribe from Sendgrid');
}
}

class NewsLetterSubscriptionsController
{
public function store(Newsletter $newsletter)
{
$newsletter->subscribe('abc@g.com');
}
}

$newsletter = new NewsLetterSubscriptionsController();
$newsletter->store(New Sendgrid());

In the code above you see, we create an interface called Newsletter and the class implements Newsletter interface must use subscribe method. By using Interface we force the developer to use the methods we need to use.

Overall, interfaces are a fundamental tool in object-oriented programming that helps improve code organization, maintainability, and flexibility. They enable you to design more modular and extensible software by defining clear boundaries and contracts between different parts of your code.

For more details of OOP (Object Ordinated Programming) , you may have a look at the link given below. Feel free to leave a comment if you have any feedback or questions.

https://github.com/mohasin-dev/Object-Oriented-Programming-in-PHP

Bonus: You must love my most read article : How To Use Single Responsibility Principle in PHP/Laravel
And most GitHub star repo:
https://github.com/mohasinhossain/SOLID-Principles-in-PHP

--

--

Mohasin Hossain

Senior Software Engineer | Mentor @ADPList | Backend focused | PHP, JavaScript, Laravel, Vue.js, Nuxt.js, MySQL, TDD, CI/CD, Docker, Linux