typestar

Interfaces in PHP

One contract, two shapes, one loop that cares about neither.

<?php
interface Shape {
    public function area(): float;
}

class Circle implements Shape {
    public function __construct(private float $r) {}
    public function area(): float { return M_PI * $this->r ** 2; }
}

class Square implements Shape {
    public function __construct(private float $side) {}
    public function area(): float { return $this->side ** 2; }
}

foreach ([new Circle(1.0), new Square(2.0)] as $shape) {
    printf("%.2f\n", $shape->area());
}

How it works

  1. interface Shape promises an area method and nothing else.
  2. Circle and Square each satisfy it with their own geometry.
  3. The loop treats both as Shape — polymorphism without inheritance.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
443
Tokens
102
Three-star pace
80 tpm

At the three-star pace of 80 tokens a minute, this run takes about 76 seconds.

Type this snippet

Step 2 of 3 in Classes, step 17 of 27 in Language basics.

← Previous Next →

Interfaces in other languages