DEV Community

Cover image for PHP - What are Interfaces?
Md Parvez Ahmmed
Md Parvez Ahmmed

Posted on

PHP - What are Interfaces?

Interfaces allow you to specify and pre-declare what methods a class should implement.
Interfaces make it easy to use various classes in the same way. When one or more classes use the same interface, it is called "polymorphism".
Interfaces are declared with the interface keyword before the Interfaces name:
Example Below:

<?PHP
//interface definition
interface Animal {
  public function makeSound();
}
//interface implements is another class
class Cat implements Animal {
  public function makeSound() {
    echo "Meow";
  }
}

$animal = new Cat();
$animal->makeSound();
?>
Enter fullscreen mode Exit fullscreen mode

From the example above, let's say that we would like to write software that manages a group of animals. There are actions that all of the animals can do, but each animal does it in its way.
Using interfaces, we can write some code which can work for all of the animals even if each animal behaves differently:

<?php
// Interface definition
interface Animal {
  public function makeSound();
}

// Class definitions with implement interface
class Cat implements Animal {
  public function makeSound() {
    echo " Meow ";
  }
}

class Dog implements Animal {
  public function makeSound() {
    echo " Bark ";
  }
}

class Mouse implements Animal {
  public function makeSound() {
    echo " Squeak ";
  }
}

// Create a list of animals
$cat = new Cat();
$dog = new Dog();
$mouse = new Mouse();
//all animals/classes are to be stored in an array.
$animals = array($cat, $dog, $mouse);

// Tell the animals to make a sound
foreach($animals as $animal) {
  $animal->makeSound();
}
?>
Enter fullscreen mode Exit fullscreen mode

Example Explained
Cat, Dog and Mouse are all classes that implement the Animal interface, which means that all of them can make a sound using the makeSound() method. Because of this, we can loop through all of the animals and tell them to make a sound even if we don't know what type of animal each one is.

Since the interface does not tell the classes how to implement the method, each animal can make a sound in its way.

Top comments (0)