What role do interfaces play in PHP programming and how can they be effectively utilized in class design?
Interfaces in PHP programming define a contract for classes to implement certain methods. They help in achieving abstraction and loose coupling between classes, making the code more modular and easier to maintain. Interfaces can be effectively utilized in class design by defining common methods that classes must implement, allowing for polymorphism and flexibility in the code structure.
<?php
// Define an interface with common methods
interface Shape {
public function calculateArea();
public function calculatePerimeter();
}
// Implement the interface in a class
class Circle implements Shape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function calculateArea() {
return pi() * $this->radius * $this->radius;
}
public function calculatePerimeter() {
return 2 * pi() * $this->radius;
}
}
// Create an object of the class and call the interface methods
$circle = new Circle(5);
echo "Area: " . $circle->calculateArea() . "\n";
echo "Perimeter: " . $circle->calculatePerimeter();
?>