Readonly & first-class callables in PHP
Immutable properties and the (...) syntax that lifts any callable.
<?php
final class Point {
public function __construct(
public readonly float $x,
public readonly float $y,
) {}
public function length(): float {
return sqrt($this->x ** 2 + $this->y ** 2);
}
}
$p = new Point(3.0, 4.0);
echo $p->length(), "\n";
// first-class callable syntax turns any function into a closure
$len = $p->length(...);
echo $len(), "\n";
echo implode(" ", array_map(strtoupper(...), ["read", "only"])), "\n";
How it works
readonlypromoted properties are set once in the constructor.lengthcomputes from$this->xand$this->y, never mutating.$p->length(...)turns the method into a closure to call later.strtoupper(...)hands a named function straight toarray_map.
Keywords and builtins used here
Pointarray_mapclassechofinalfunctionimplodelengthnewpublicreadonlyreturnsqrtstrtoupper
The run, in numbers
- Lines
- 19
- Characters to type
- 426
- Tokens
- 104
- Three-star pace
- 75 tpm
At the three-star pace of 75 tokens a minute, this run takes about 83 seconds.
Step 3 of 3 in Modern touches, step 24 of 27 in Language basics.