PHP OOP - Interfaces


PHP - What are Interfaces?

Visual connectors allow you to specify which methods the class should use.

The interface makes it easy to use different classes in the same way. When one or more class uses the same visual connector, it is called a "polymorphism".

Interfaces are announced by the interface keyword:


Syntax
<?php
interface InterfaceName {
  public function someMethod1();
  public function someMethod2($name, $color);
  public function someMethod3() : string;
}
?>


PHP - Interfaces vs. Abstract Classes

Visible connector is similar to invisible classes. The differences between interfaces and abstract classes are:

  • Interactions cannot have structures, while invisible classes can
  • All interactions should be public, while abstract class methods are public or protected
  • All methods in the interface are abstract, so they cannot be coded and an invisible keyword is not required.
  • Classes can use a visual connector while benefiting from another class at the same time

PHP - Using Interfaces

In order to use the interface, the class must use the keyword of the implements.

The communication class should use all the interface modes.


Example
<?php
interface Animal {
  public function makeSound();
}

class Cat implements Animal {
  public function makeSound() {
    echo "Meow";
  }
}

$animal = new Cat();
$animal->makeSound();
?>

From the example above, let's say we'd like to write software that manages a group of animals. There are actions that every animal can do, but each animal does it in its own way.

Using meeting places, we can write code that can apply to all animals even if each animal behaves differently:


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

// Class definitions
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();
$animals = array($cat, $dog, $mouse);

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

Example Explained

Cat, Dog and Mouse all classes use the Visual Animal Connector, which means they can all make sound using the makeSound() method. Because of this, we can get into every animal and tell them to make a noise even if we do not know what kind of animal they are.

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