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
interface Shapepromises anareamethod and nothing else.CircleandSquareeach satisfy it with their own geometry.- The loop treats both as
Shape— polymorphism without inheritance.
Keywords and builtins used here
CircleSquareareaasclassforeachfunctionimplementsinterfacenewprintfprivatepublicreturn
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.
Step 2 of 3 in Classes, step 17 of 27 in Language basics.