Interface in PHP with Examples

An interface in PHP is simply a contract that defines a set of methods without implementations. It enforces a contract for what a class can do, without dictating how it does it.

Any class that implements an interface must implement all the methods defined in that interface. An interface can only contain a set of public method signatures and constants that a class must implement. All interface methods are public by default.

In object-oriented programming (OOP), an interface is a powerful feature that provides well-structured code, consistency, and contract enforcement to code. This feature promotes clean architecture, supports design patterns, improves code reusability, and enhances maintainability.

Why Use Interfaces in PHP?


Interfaces are widely used in real-world PHP applications, frameworks, and APIs. The following are the key benefits of using interfaces in PHP:

  • Achieves full abstraction by defining method contracts without implementations.
  • Supports multiple inheritance by allowing a class to implement multiple interfaces.
  • Improves code reusability, flexibility, and maintainability.
  • Makes code loosely coupled, reducing dependencies between components.
  • Helps in dependency injection and improves testability.
  • Enforces a standard and clean structure across classes.

Basic Syntax of Interface in PHP


To declare an interface in PHP, we use interface keyword, followed by the interface name and a block containing the public method declarations. The general syntax for defining an interface in PHP is as:

interface InterfaceName {
    public function methodName();
}

In the above syntax:

  • All methods defined in an interface are implicitly public.
  • Methods declared in an interface cannot have a body (implementation).
  • Interfaces cannot have properties, but they may contain constants.

Example:

<?php
interface Shape {
   public function calculateArea();
   public function calculatePerimeter();
}
?>

In this example:

  • Shape is an interface declared using the interface keyword.
  • Both methods are implicitly public even though public is written.
  • Methods contain no implementation (i.e. no method body).
  • No properties (variables) are allowed inside an interface.

Implementing Interface in a Class


A class in PHP implements an interface using the implements keyword. When an interface is implemented by a class, the class must provide the implementation for all methods defined inside the interface that are inherited. Let us take an example on it.

Example 1: Implementing an Interface in a Class

<?php
interface Shape {
   public function calculateArea();
   public function calculatePerimeter();
}
class Rectangle implements Shape {
   public function calculateArea() {
      return 10 * 5;
   }
   public function calculatePerimeter() {
      return 2 * (10 + 5);
   }
}
// Creating an object of class Rectangle.
$rec = new Rectangle();
// Calling methods.
echo "Perimeter of Rectangle = ". $rec->calculatePerimeter() . "\n";
echo "Area of Rectangle = " . $rec->calculateArea() . "\n";
?>

Output:

Perimeter of Rectangle = 30
Area of Rectangle = 50

In this example:

  • We have defined an interface named Shape, which declares two method signatures: calculateArea() and calculatePerimeter() without providing any implementations.
  • The Rectangle class implements the Shape interface using the implements keyword. It provides concrete implementations for all the methods declared in the interface.
  • Then, we create an object of the class Rectangle that implements the interface and call its methods on a Rectangle object.
  • All methods remain public, as required by the interface.
  • We cannot reduce the visibility of interface methods in the implementing class.
Note:

When a class (or abstract class) implements an interface, method signatures must match exactly. However, parameter names can be different.

  • Method name → must match
  • Number of parameters → must match
  • Parameter types (if used) → must match
  • Return type (if declared) → must match
  • Access level → must be public

Example 2: Multiple Classes Implementing Same Interface

<?php
interface PaymentMethod {
   public function pay($amount);
}
class CreditCard implements PaymentMethod {
   public function pay($amount) {
      echo "Paid $amount using Credit Card \n";
   }
}
class PayPal implements PaymentMethod {
   public function pay($amount) {
     echo "Paid $amount using PayPal \n";
   }
}
class UPI implements PaymentMethod {
   public function pay($amount) {
     echo "Paid $amount using UPI \n";
   }
}
$cc = new CreditCard();
$pp = new PayPal();
$upi = new UPI();

$cc->pay("$500");
$pp->pay("$600");
$upi->pay("$1000");
?>

Output:

Paid $500 using Credit Card 
Paid $600 using PayPal 
Paid $1000 using UPI

This example demonstrates polymorphism in PHP. In this example:

  • We have defined an interface named PaymentMethod that defines a common method pay().
  • Multiple classes, such as CreditCard, PayPal, and UPI implement the same interface PaymentMethod.
  • Each class provides its own specific implementation of the pay() method.
  • All classes follow the same method signature, ensuring consistency.
  • Adding a new payment method later does not affect existing code.

Example 3: Interface with Constants and Methods

<?php
interface Shape
{
// Interface constant
   const PI = 3.14159;
// Method declarations.
   public function calculateArea();
     public function calculatePerimeter();
   }
class Rectangle implements Shape
{
   private float $length;
   private float $width;

   public function __construct(float $length, float $width)
   {
     $this->length = $length;
     $this->width = $width;
   }
   public function calculateArea()
   {
     return $this->length * $this->width;
   }
   public function calculatePerimeter()
   {
     return 2 * ($this->length + $this->width);
   }
}
class Circle implements Shape
{
   private float $radius;
   public function __construct(float $radius)
   {
      $this->radius = $radius;
   }
   public function calculateArea()
   {
      return Shape::PI * $this->radius * $this->radius;
   }
   public function calculatePerimeter()
   {
      return 2 * Shape::PI * $this->radius;
   }
}
$rectangle = new Rectangle(10, 5);
$circle = new Circle(7);

echo "Area of Rectangle: " . $rectangle->calculateArea() . "\n";
echo "Perimeter of Rectangle: " . $rectangle->calculatePerimeter() . "\n";
echo "Area of Circle: " . $circle->calculateArea() . "\n";
echo "Perimeter of Circle: " . $circle->calculatePerimeter();
?>

Output:

Area of Rectangle: 50
Perimeter of Rectangle: 30
Area of Circle: 153.93791
Perimeter of Circle: 43.98226

In this example:

  • Shape is an interface that defines a common contract for all shapes. The interface contains:
    • A constant PI
    • Two public method declarations.
  • The classes Rectangle and Circle both implement the same interface.
  • Each class provides its own specific implementation of area and perimeter for calculations.
  • The constant PI defined in the interface is accessed using Shape::PI.

Implementing Multiple Interfaces in PHP


We know that PHP does not support multiple inheritance using classes, meaning that a class cannot extend more than one class at a time. However, PHP supports multiple inheritance through interfaces. In simple words, PHP allows to support multiple interface implementations.

Implementing multiple interfaces is the standard way to achieve multiple inheritance in PHP. It allows a class to implement multiple contracts at the same time, allowing it to inherit behavior definitions from more than one source. The basic syntax to implement multiple interface by a class in PHP is as:

class ClassName implements Interface1, Interface2 {
   // Implement all methods from both interfaces
}

Let us take an example to demonstrate how multiple inheritance can be achieved in PHP using interfaces.

Example 4: Achieving Multiple Inheritance Using Interfaces

<?php
interface Academics
{
   public function study();
}
interface Sports
{
   public function playSport();
}
// Implementing multiple interfaces by a class.
class Student implements Academics, Sports
{
   private string $name;
   public function __construct(string $name)
   {
      $this->name = $name;
   }
   public function study()
   {
      echo $this->name . " is studying computer science. \n";
   }
   public function playSport()
   {
      echo $this->name . " is playing football. \n";
   }
}
$student = new Student("Rahul");
$student->study();
$student->playSport();
?>

Output:

Rahul is studying computer science. 
Rahul is playing football.

This example demonstrates how multiple inheritance is achieved in PHP using interfaces. In this example:

  • We have defined two interfaces named Academics and Sports. Each interface defines a separate contract.
  • We then have defined a class named Student, which implements both interfaces.
  • The class Student must implement all methods declared in both interfaces.
  • The class Student inherits behavior (method) from Academics interface as well as inherits behavior from Sports interface.

This is the standard and correct way to achieve multiple inheritance in PHP using interfaces.

Interface Inheritance in PHP


An interface in PHP can extend another interface using extends keyword. This means that an interface can inherit the method contracts of another interface.

Extending one interface from another is referred to as interface inheritance in PHP. It creates a hierarchy of interfaces, which makes it convenient to organize related interfaces and define multiple levels of contracts for implementing classes.

When an interface is implemented by a class and the interface extends another interface, the class must provide implementations for all methods declared in the interface and its parent interfaces. Let us take a simple example to understand this.

Example 5: Extending an Interface

<?php
interface A {
   public function methodA();
}
interface B extends A {
   public function methodB();
}
class MyClass implements B {
// Implementation of methodA and methodB.
   public function methodA(){
     echo "This is methodA. \n";
   }
   public function methodB(){
     echo "This is methodB. \n";
   }
}
// Creating an object of class MyClass.
$myclass = new MyClass();
$myclass->methodA();
$myclass->methodB();
?>

Output:

This is methodA. 
This is methodB.

In this example:

  • The interface A contains only one method methodA() and the interface B also contains only one method methodB().
  • The interface B extends A and inherits the method contract from interface A.
  • The class MyClass implements interface B and implements methodA() and methodB() of both interfaces A and B.
  • An object of class MyClass is created and called both methods using $myclass object.

Combining Interfaces and Abstract Classes


In many cases, you may need to use interfaces and abstract classes together to define robust object-oriented structure. An abstract class can implement one or more interfaces and provide base implementations for some or all of their methods.

The classes which extend this abstract class can use these base implementations or override them according to their requirements. Let us take a simple example to understand this.

Example 6:

<?php
interface Drivable {
   public function start();
   public function stop();
   public function accelerate($increase);
}
abstract class Vehicle implements Drivable {
   protected int $speed = 0;
   public function accelerate($increase) {
     $this->speed += $increase;
     echo "Speed increased to {$this->speed} km/h. \n";
   }
}
class Car extends Vehicle {
   public function start() {
      echo "Car started. \n";
   }
   public function stop() {
      echo "Car stopped.\n";
   }
}
$car = new Car();
$car->start();
$car->accelerate(20);
$car->accelerate(30);
$car->stop();
?>

Output:

Car started. 
Speed increased to 20 km/h. 
Speed increased to 50 km/h. 
Car stopped.

In the given example:

  • Vehicle is an abstract class that implements Drivable interface.
  • It provides a base implementation for accelerate() which Car (or any other class extending Vehicle) can use directly.
  • The class Car extends Vehicle and provides implementations for start() and stop() methods.
  • The method accelerate() is inherited from the abstract class and called directly using the object $car->accelerate(20);.

When to Use Interface in PHP?


You should use interfaces in PHP when you need to:

  • Share common behavior (method signatures) across multiple classes.
  • Achieve loose coupling and reduce dependency between classes.
  • Allow different classes to provide their own implementations of the same behavior.
  • Use interfaces to define extensible behavior that classes can implement differently.
  • Achieve multiple inheritance through interfaces.
  • Work with framework-based architecture.

Interfaces vs Abstract Classes in PHP


Interfaces and abstract classes are both used to achieve abstraction in PHP. However, they differ in several ways:

  • Interfaces cannot have properties, whereas abstract classes can.
  • All interface methods must be public, while abstract class methods can be public or protected.
  • Interfaces cannot contain method implementations, but abstract classes can.
  • A class can implement multiple interfaces but can extend only one abstract class.
  • Interfaces cannot have constructors, whereas abstract classes can.
  • Interfaces define a contract, while abstract classes provide a base implementation.

Conclusion

Interface in PHP is a core object-oriented programming concept, which provides a contract for classes to promote design patterns, code reusability and maintainability. By using interfaces and abstract classes, you can create more structured, maintainable and robust PHP applications.

We hope this article has helped you understand the fundamental concepts of interfaces in PHP and practice the examples discussed above.

DEEPAK GUPTA

DEEPAK GUPTA

Deepak Gupta is the founder of Scientech Easy and a passionate coding educator with 8 years of professional experience in Java, Python, web development, and core computer science subjects. With expertise in full-stack development, he provides hands-on training in programming languages and in-demand technologies at the Scientech Easy Institute, Dhanbad.

He consistently publishes in-depth tutorials, practical coding examples, and valuable learning resources for beginners as well as working professionals. Each article is carefully researched and reviewed to ensure accuracy, quality, and real-world relevance.