PHP Interfaces
Interfaces in PHP are contracts that define a set of methods that a class must implement. They allow for a form of multiple inheritance, enabling a class to implement multiple interfaces.
Benefits of Using Interfaces
- Enforces a contract: Classes that implement an interface must define all its methods.
- Supports multiple inheritance: A class can implement multiple interfaces.
- Promotes loose coupling: Interfaces allow for more flexible code and easier maintenance.
Example of Interfaces
<?php
interface Animal {
public function speak();
}
class Cat implements Animal {
public function speak() {
return "Cat meows";
}
}
class Dog implements Animal {
public function speak() {
return "Dog barks";
}
}
$cat = new Cat();
echo $cat->speak(); // Outputs: Cat meows
$dog = new Dog();
echo $dog->speak(); // Outputs: Dog barks
?>
Output:
Cat meows
Dog barks
Explanation: In this example, the Animal
interface defines a speak
method. Both the Cat
and Dog
classes implement this interface and provide their own implementations of the speak
method. When called, each class outputs its respective sound.