Interfaces in PHP
<?php
// Here's a basic interface for geometric shapes.
interface Geometry {
public function area(): float;
public function perim(): float;
}
// For our example we'll implement this interface on
// `Rect` and `Circle` classes.
class Rect implements Geometry {
private float $width;
private float $height;
public function __construct(float $width, float $height) {
$this->width = $width;
$this->height = $height;
}
public function area(): float {
return $this->width * $this->height;
}
public function perim(): float {
return 2 * $this->width + 2 * $this->height;
}
}
class Circle implements Geometry {
private float $radius;
public function __construct(float $radius) {
$this->radius = $radius;
}
public function area(): float {
return M_PI * $this->radius * $this->radius;
}
public function perim(): float {
return 2 * M_PI * $this->radius;
}
}
// If a variable has an interface type, then we can call
// methods that are in the named interface. Here's a
// generic `measure` function taking advantage of this
// to work on any `Geometry`.
function measure(Geometry $g) {
echo get_class($g) . "\n";
echo $g->area() . "\n";
echo $g->perim() . "\n";
}
$r = new Rect(3, 4);
$c = new Circle(5);
// The `Circle` and `Rect` classes both
// implement the `Geometry` interface so we can use
// instances of these classes as arguments to `measure`.
measure($r);
measure($c);In PHP, interfaces work similarly to how they do in other object-oriented languages. Here’s an explanation of the key points:
We define an interface
Geometrywith two method signatures:area()andperim().We create two classes,
RectandCircle, both of which implement theGeometryinterface.Each class provides its own implementation of the
area()andperim()methods.We define a
measure()function that takes any object implementing theGeometryinterface. This function can work with bothRectandCircleobjects.In the main part of the script, we create instances of
RectandCircleand pass them to themeasure()function.
To run this program, save it as interfaces.php and execute it with PHP:
$ php interfaces.php
Rect
12
14
Circle
78.539816339745
31.415926535898This example demonstrates how interfaces in PHP allow for polymorphism, enabling you to write more flexible and reusable code. By defining a common interface, you can create functions that work with any object that implements that interface, regardless of its specific class.