PHP Interfaces

PHP Interfaces

Interfaces allow you to specify what methods a class should implement.

They act as a strict contract. If a class promises to implement an interface, it must provide the exact functions defined within that interface.


Creating and Implementing Interfaces

Interfaces are declared with the interface keyword. To implement an interface, a class must use the implements keyword.

Interface Example

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

// Class implementing the interface class Cat implements Animal { public function makeSound() { echo "Meow"; } }

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


Interfaces vs. Abstract Classes

They seem similar, but have crucial differences:

  1. Multiple Implementation: A class can only inherit from one abstract parent class, but a class can implement multiple interfaces at the same time (e.g., class Mouse implements Animal, Pest).
  2. No Properties: Interfaces cannot have properties/variables, while abstract classes can.
  3. No Logic: Interfaces cannot have any code inside their methods. They only declare the method names. Abstract classes can contain regular methods with fully written code.
  4. Always Public: All methods declared in an interface must be public.

Use interfaces when you need many completely unrelated classes to share the exact same method names!