Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

PHP Interfaces

PHP – What are Interfaces?

Interfaces specify the methods that a class must implement, making it easy to use different classes in the same way. When multiple classes implement the same interface, it is known as “polymorphism”.

Interfaces are declared using the interface keyword:

Syntax

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

PHP – Interfaces vs. Abstract Classes

Interfaces are similar to abstract classes, but there are key differences:

  • Interfaces cannot have properties, whereas abstract classes can.
  • All interface methods must be public, while abstract class methods can be public or protected.
  • All methods in an interface are abstract, so they cannot have implementations and do not need the abstract keyword.
  • A class can implement multiple interfaces while also inheriting from a single class.

PHP – Using Interfaces

To implement an interface, a class must use the implements keyword.

A class implementing an interface must implement all the methods defined by that interface.

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 want to write software to manage a group of animals. There are actions that all animals can perform, but each animal does them in its own way.

Using interfaces, we can write code that works for 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 are all classes that implement the Animal interface, which means they can all make a sound using the makeSound() method. This allows us to loop through all the animals and instruct them to make a sound, even if we don’t know the type of animal each one is.

Since the interface does not dictate how the method should be implemented, each animal can make a sound in its own unique way.