Skip to main content

PHP Interfaces

An interface is a list of public methods that a class MUST provide. It says what has to exist but leaves out how each method works.

You declare one with the interface keyword, and every method in it has to be public.

A class signs up for an interface with the implements keyword, and from then on it has to implement all of the interface's methods.

In the next example, the Animal interface declares a single public method, makeSound(). Because Cat and Dog both implement Animal, each of them has to include makeSound():

Example

Cat and Dog each give makeSound() their own body to satisfy the Animal interface:

Prompt
Create a PHP interface Animal with a makeSound() method. Create Cat and Dog classes that implement the Animal interface and echo their sounds. Create objects and call makeSound() on each.
Output: PHP script

Interface syntax

How an interface declaration is written:

index.php
<?php
interface InterfaceName {
  public function method1();
  public function method2();
}
?>

Implementing an interface

How a class implements an interface:

index.php
<?php
class ClassName implements InterfaceName{
  public function method1() {
    // some code
  }
  public function method2(){
    // some code
  }
}
?>

PHP - Interfaces vs. Abstract Classes

Interfaces have a lot in common with abstract classes, but they differ in several ways:

  • An abstract class can have properties; an interface cannot
  • Interface methods are always public, whereas abstract methods may be public or protected
  • Every interface method is abstract, so it has no implementation in code, and you don't need to write the abstract keyword
  • A class can extend another class and implement an interface at the same time

The big benefit of interfaces is that different classes can be used in the same way. When one or more classes share an interface, we call this "polymorphism".


PHP - Using Interfaces

This time the Animal interface declares two public methods, fromFamily() and makeSound(). Cat and Dog implement the interface, so each class has to include both methods:

Example

Cat and Dog both implement the two methods of the interface:

Prompt
Create a PHP interface Animal with fromFamily() and makeSound() methods. Create Cat and Dog classes that implement both methods with detailed family info and sounds. Create objects and call both methods.
Output: PHP script