Interfaces in PHP provide a way to define a contract for classes to follow, specifying which methods a class must implement without providing the implementation details. Let’s illustrate interfaces and how classes implement them with an example:
// Define the interface
interface Animal {
public function makeSound();
}
// Implement the interface in a class
class Dog implements Animal {
public function makeSound() {
return "Woof! Woof!";
}
}
class Cat implements Animal {
public function makeSound() {
return "Meow! Meow!";
}
}
// Create instances of the classes and call the method
$dog = new Dog();
echo $dog->makeSound(); // Output: Woof! Woof!
$cat = new Cat();
echo $cat->makeSound(); // Output: Meow! Meow!
Explanation:
Animal
with a single method makeSound()
.Dog
and Cat
classes implement the Animal
interface by providing an implementation for the makeSound()
method.makeSound()
method according to the behavior of the animal.Dog
and Cat
classes and call the makeSound()
method on them, we get the specific sound associated with each animal.Interfaces allow for polymorphism, where different objects can be treated interchangeably based on the interface they implement. It promotes code reusability and flexibility in object-oriented designs.
Leave A Comment