In PHP, an interface is a powerful language construct that allows us to declare a set of methods that must be implemented by any class that adopts the interface. It defines a contract that a class must adhere to, specifying the methods that the class must implement without providing the actual implementation. Essentially, an interface defines a blueprint for a group of related functionalities.
Here’s a basic example of how an interface is defined in PHP:
// Define the Shape interface
interface Shape {
public function calculateArea();
public function calculatePerimeter();
}
In the above example:
Shape
is the interface, and it declares two methods vizcalculateArea
andcalculatePerimeter
.Circle
andSquare
are classes that implement theShape
interface. They must provide an implementation for thecalculateArea
andcalculatePerimeter
method defined in the interface.
A class can implement multiple interfaces, and an interface can extend other interfaces. This allows you to organize your code in a modular and reusable way. I will explain this in another article.
// Implement the Shape interface in the Circle 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 pi() * $this->radius * $this->radius;
}
}
// Implement the Shape interface in the Square class
class Square implements Shape {
private $side;
public function __construct($side) {
$this->side = $side;
}
public function calculateArea() {
return $this->side * $this->side;
}
public function calculatePerimeter() {
return 4 * $this->side;
}
}
// Create objects and calculate areas
$circle = new Circle(5);
$square = new Square(4);
echo "Circle Area: " . $circle->calculateArea() . "\n";
echo "Circle Perimeter: " . $circle->calculatePerimeter() . "\n";
echo "Square Area: " . $square->calculateArea() . "\n";
echo "Square Perimeter: " . $square->calculatePerimeter() . "\n";
Now, you can create objects of Circle
and Square
and calculate both the area and perimeter using the methods provided by the Shape
interface. This demonstrates how interfaces can be extended to include additional methods while ensuring that implementing classes adhere to the new contract.