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:

  1. We define an interface Geometry with two method signatures: area() and perim().

  2. We create two classes, Rect and Circle, both of which implement the Geometry interface.

  3. Each class provides its own implementation of the area() and perim() methods.

  4. We define a measure() function that takes any object implementing the Geometry interface. This function can work with both Rect and Circle objects.

  5. In the main part of the script, we create instances of Rect and Circle and pass them to the measure() 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.415926535898

This 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.