Skip to content
Home » Using Interfaces in PHP Like a Pro with Code Examples in 2023

Using Interfaces in PHP Like a Pro with Code Examples in 2023

What is an interface in PHP?

Interface in PHP or more generally in Object Oriented Programming (OOP) is an idea of having a higher level of representation or more precisely an abstraction over more specialized and concrete classes. That sounds like a philosophical thing. 

Worry not, because we have a lot to say about interfaces and what they are in Object Oriented Programming (OOP). Stay tuned till the end to learn more.

PHP Object-Oriented Programming Learning Path

This article is part of our series on learning Object-oriented programming with PHP. It introduces some concepts, best practices and strategies to help you level up your skills. This is a great intro to growing into a successful programmer.

What’s with the term ‘interface’?

The term ‘interface’ changes meaning in different contexts. Perhaps, that’s a reason why it is often a misunderstood term. So, let’s see the different meanings of this term in different contexts.

interface PHP

User Interface / User Experience (UI/UX)

Designers use the term interface for visible and interactive elements of an application, more generally called the ‘Frontend’ of an application. In fact, the ‘User Interface’ (UI) is an important aspect of human & machine interactions. A bad UI affects ‘User Experience (UX)’, nobody wants to see laggy and outdated UIs these days.

Hardware interface

Hardware also has the term ‘interface’. What do they really mean by it? A very typical example will be a TV remote, an interface to all the functions of a TV. It hides all the underlying electrical circuits and complexities that are not meant for the end users. So, it has some buttons with clear intended functions and users don’t really care what lies beneath as long as the remote provides them with an interface to the TV functions.

Interface in OOP

Object Oriented Programming (OOP) defines interface as an idea of having a higher level of representation or more precisely an abstraction over more specialized and concrete classes. That sounds like a philosophical thing. Let’s follow an example and learn more about this seemingly complex idea.

The example features an interface Shape having sub-classes Square and Circle.  The Client module uses (has-a) Shape object rather than any of the specialized classes. But does it really make a difference to dive into specifics and make your software modules tied to specific instances? 

shapes

A Square is a shape and so is a Circle so what if the module refers to all of them as Shapes than worrying much about what type they are exactly? Why would we do this? For now, just bear in mind that a good software design is more flexible and thus more generalized.    

So, the interface Shape is a generalization that wraps over specifications. Though there are some other OOP concepts that allow us to use generalizations but more on that in a later section.

An Abstract Idea of Interfaces

So, we have seen different meanings of the term ‘interface’ but what is a common theme or more precisely the abstract idea of this term? In layman’s terms, an interface is:

  • Point of contact or interaction between two entities
  • Hides the underlying details and infrastructure.
  • Simplifies the complexity of a system and makes it more usable.

Using Interface in PHP with Code Examples

We have understood the concept of interface and have seen generalization but how to use interfaces in PHP? How do we define it? What’s the syntax? Let’s answer these questions one by one.

What is an interface in PHP?

Interfaces in PHP or any other programming language define a type with function declarations having no implementation. Any class which implements an interface has to implement these functions. 

Think of it as a contract, a class can implement an interface but if it does so, it is responsible for implementing these functions defined in that interface.

Shape interface PHP Code Example

Let’s fall back to the same example and define a Shape interface in PHP. Interfaces are declared with the keyword interface followed by a name.

<?php


interface Shape {


    //Funtion declaration
    public function getArea();
}


?>

The function getArea() is a function declaration. Any class which would implement Shape will have to implement this function.

No implementation, weird much?

At this point, that’s a question in everyone’s mind, “If we are not implementing something why are we delcaring it in the first place?” And the answer is “Polymorphism”

Polymorphism is an OOP concept that means an object which occurs in different forms. Remember a Circle is a Shape so is a Square meaning that they may have different forms but they have a common supertype. Or inversely, a Shape can have different forms.

Programmatically, you can define a Shape object and can assign it a Circle or a Square. You can also call getArea() on both these, because they are shapes and shapes have areas or more technically they implement Shape and have to implement getArea().

Implementing Shape interface in PHP

A class has to use the implements keyword followed by the interface name.

class Circle implements Shape {
   
    //Can define additional properties & methods
    private $PI = 3.14159;
    private $radius;


    function __construct($r) {
        $this->radius = $r;
    }


    //Implements the getArea()
    public function getArea() {
        return ($this->PI * ($this->radius)**2); //Area of a circle is πr^2
    }
}


class Square implements Shape {
   
    //Can define additional properties & methods
    private $length;
    private $width;


    function __construct($l, $w) {
        $this->length = $l;
        $this->width  = $w;
    }


    //Implements the getArea()
    public function getArea() {
        return $this->length * $this->width; //Area of a square is length x width
    }
}

Both Circle and Square have a common supertype Shape. The following example uses both of them polymorphically by using the supertype.

circle = new Circle(2);
$square = new Square(2,2);




//If Cirlce has a Shape type.
if($circle instanceof Shape) {
    echo 'Circle is of type Shape'.PHP_EOL;
    echo 'Circle has an area of '.$circle->getArea().' square units'.PHP_EOL;
}




//If Square has a Shape type.
if($square instanceof Shape) {
    echo 'Square is of type Shape'.PHP_EOL;
    echo 'Square has an area of '.$square->getArea().' square units'.PHP_EOL;
}

Circle and Square are both instances of Shape and the output is what we would expect the most.

Circle is of type Shape
Circle has an area of 12.56636 square units
Square is of type Shape
Square has an area of 4 square units

That’s polymorphism but it is not apparent what did we achieve from it, right? Let’s see what are some of the benefits of interfaces.

Benefits of an interface in PHP

Flexibility & extensibility

The interface is a generalization, an entity that sits at the top of a hierarchy and all the succeeding classes inherit (extend) it. This idea of a supertype in a hierarchy and referring to all the sub-classes in terms of that superclass is what we call polymorphism.

But how does that makes our system more flexible? Well, if your module is bound to a specific type of Circle, then it may not function as intended with a Square unless you make lots of changes to the existing codebase and open ways for bugs to creep in. Also, that is a violation of one of the design principles called the Open-closed principle.

The open-closed principle states that “a class should be open for extension but closed for modification.”  That’s nearly impossible when you stick with a specialized type like Circle because you have to make changes when other concrete Shape types come into the picture.

Having an interface allows us to refer to these sub-types in terms of a superclass, for instance, Shape, and treat all of them based on what the Shape interface allows us to do. This way we can add many shapes without having to modify the existing code and effortlessly extend our code.

Another valuable design principle says, ‘program to interface than implementations’ which is based on a similar idea. It states that classes should refer in terms of interfaces so the system remains flexible.

Usability & Cohesion

The interface also encapsulates (hides) the underlying details like data types or implementations. So, when a class refers to an interface it has the benefit of not worrying much about what data structures have been used or how things work the way they work.

For example, in the example, above we are not much concerned about how a Circle calculates its area or how differently a Square does the same. All we know is that they are Shapes and they must return a numeric value when we call getArea() on them.

This idea of encapsulation makes a class more cohesive meaning that it does similar functions or takes up a similar kind of responsibility than doing a lot more than it is supposed to do and that’s what another design principle Single responsibility principle states that a class should have one and only one responsibility.

Another aspect of this cohesiveness is that when your class is one unit having similar responsibilities and fewer dependencies, it has fewer reasons to change. They are least affected when some other aspects of the code change. 

Confining a change or limiting the scope of the change in a software system yields benefits in the long run when you have change requests or when you want to add features to your software system. 

Last but not the least, they are much easier and simpler than concrete classes with mind-boggling levels of detail. If all you need is to use a black box then why bother diving into details? 

Interfaces vs Abstract Classes in PHP

Interface and abstract classes are somewhat similar but they do have a few differences.

InterfaceAbstract Classes
They don’t have attributes or fields They can have attributes or fields
Interfaces don’t have concrete methods, they just declare them.Abstract classes can have concrete methods
Functions have to be publicFunctions can be public or protected
All methods are abstract, declared only and they don’t need to have the abstract keyword in their signatures.One or more methods can be abstract and has to have the abstract keyword in their signatures.
Classes implement an interface.Classes inherit abstract classes.

When to use an interface in PHP?

  • When you want to decouple your modules from concrete instances.
  • When you want to have a more flexible and extendible system.
  • Interfaces are used to implement most of the design patterns.
  • When you want to test your program more easily and efficiently using mock objects and stubs leveraging polymorphism.

Frequently Asked Questions

How to use an interface in PHP?

To use an interface in PHP you have to declare it using the interface keyword followed by a name. Classes then implement it and provide implementations for the abstract methods of that interface.

<?php


interface Animal {


   public function makeSound();
}


class Cat implements Animal {


   public function makeSound() {
       echo "Meow".PHP_EOL;
   }
}




?>

Why should we use an interface in PHP?

The interface allows us to work with objects polymorphically and therefore programming to interfaces than implementations allows us to design more flexible and extendible systems. They also provide a layer of abstraction over implementations and allow us to enhance the usability of the software.

How to call interface methods in PHP?

You can call methods of an interface on the sub-classes that implement them. You don’t have to initialize concrete objects rather declare a variable of the interface type and pass it on a sub-class reference. You can call interface methods on that variable and it will behave based on the implementation layer underneath. See example.

<?
$cat = new Cat();


//Just to demonstrate that cat is an instance of Animal class (generally).
if($cat instanceof Animal) {
   $cat->makeSound(); //meow
}
?>

Using Interface in PHP Like a Pro

The article is all about interfaces in PHP. We have seen that interface can be a confusing term owing to the fact that it means different things in different contexts but the baseline is that it is something that is layered over something else that is more complicated.

In Object Oriented Programming (OOP) abstraction and encapsulation are terms more often used to encourage software developers to hide unnecessary details and expose a more simplified representation. These ideas are supported via concepts like polymorphism and inheritance which are yet another fundamental OOP concept.

Interfaces are based on the same idea of providing encapsulation and abstraction using polymorphism or generalization if we put it in less technical terms. Interface sits at the top of a hierarchy and acts as a super-entity or a layer over more concrete entities.

The article supports these ideas with an example of a Shape interface that abstracts the underlying concrete instances, Circle and Square. A software module doesn’t really bother about these concrete instances, it refers to the Shape only.

Interfaces are beneficial in terms of flexibility and extensibility of software and make maintenance and change processes less hectic. 

So, that’s all for now. Hope you have enjoyed the article. Stay tuned at FuelingPHP.

Get Deeper with PHP

We have many fun articles related to PHP. You can explore these to learn more about PHP.