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.
Interfaces are declared with the interface keyword. To implement an interface, a class must use the implements keyword.
<?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();
?>
They seem similar, but have crucial differences:
class Mouse implements Animal, Pest).public.Use interfaces when you need many completely unrelated classes to share the exact same method names!