DEV Community

Eelco Verbrugge
Eelco Verbrugge

Posted on

PHP Interfaces Explained

Recently I wrote this blog PHP Abstract Classes Explained. Today I'll tell you about the basics of Interfaces.

Interfaces

Interface classes are used to describe the requirements for other classes to implement. Used as a contract or blueprint for objects with the same behavior.

Interfaces exists of methods and possibly constants. Methods are defined, but not implemented. To better understand I'll explain this by an example.

For example

Let say I own a dog and a cat and their behavior is making noise when getting hungry:

class John
{
    public function bark()
    {
        echo 'Woef!';
    }
}

class Jane
{
    public function meow()
    {
        echo 'Meow!';
    }
}
Enter fullscreen mode Exit fullscreen mode

Obviously dogs and cats make different noises... However their need for food is equal and so this behavior can be captured in an interface:

interface Dog
{
    public function eat(string $food);
}

interface Cat
{
    public function eat(string $food);
}
Enter fullscreen mode Exit fullscreen mode

In order to use our interface we add implements to our classes:

class John implements Dog
{
    public function bark()
    {
        echo 'Woef!';
    }

    public function eat(string $food)
    {
        echo sprintf('I love eating ', $food);
    }
}

class Jane implements Cat
{
    public function meow()
    {
        echo 'Meow!';
    }

    public function eat(string $food)
    {
        echo sprintf('I love eating ', $food);
    }
}
Enter fullscreen mode Exit fullscreen mode

Let's confirm if John is a dog or cat:

$john = new John;

if ($john instaceof Dog) {
    echo $john->eat("bones"); // I love eating bones!
}
Enter fullscreen mode Exit fullscreen mode

Well thanks but why the need to check? Great question.

The power of interfaces

Whenever using our instances (dog or cat) in a function to feed, it is usable to check if it is a dog or cat cause their differences in diets. My dog loves eating bones, but my cat not!

Lets type-hint our class instance when passed into a function:

public function feedDog(Dog $dog)
{
    $dog->eat('bones');
}

feedDog($john); // I love eating bones!
Enter fullscreen mode Exit fullscreen mode

By doing this we ensure that whatever is passed to this function is an implementation of the Dog interface. If we wouldn't type-hint the interface, I could potentially pass a class instance in the future that doesn't have an eat() method and my pet wouldn't survive for long. So we protected our code with the requirement of eat() method to every new Dog instance.

Let me know

This gave you the basic understanding of interfaces. Please let me know if I missed something or you think this code can be better. Or what I should write about next time!

Discussion (0)