HOME HTML EDITOR C JAVA PHP

PHP OOP Interfaces

Interfaces allow you to specify which methods a class must implement, without having to define how these methods are handled. They are used to create a common standard for different classes.

1. What is an Interface?

Think of an interface as a contract. If a class "signs" the contract (implements the interface), it promises to provide code for all the methods listed in that interface.

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

2. Interface Rules

3. Practical Example

In this example, different animals must implement the makeSound() method, but each will do it in its own way:

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

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

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

$cat = new Cat();
$dog = new Dog();
$animals = array($cat, $dog);

foreach($animals as $animal) {
  $animal->makeSound();
}
?>

4. Interface vs. Abstract Class

While both force child classes to implement methods, they serve different purposes:

Feature Interface Abstract Class
Multiple Inheritance A class can implement many interfaces. A class can extend only one class.
Functionality Cannot contain any code or logic. Can contain logic and regular methods.
Properties Cannot have variables. Can have variables.

5. Why Use Interfaces?

Interfaces enable Polymorphism. This means you can write code that works with any object that follows a specific interface, without caring about the actual class of the object. It makes your application highly decoupled and easy to extend.

Pro Tip: Interfaces are great for defining "capabilities." For example, an interface named Exportable could force classes like Invoice or UserReport to provide an exportToPDF() method.