typestar

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

  1. readonly promoted properties are set once in the constructor.
  2. length computes from $this->x and $this->y, never mutating.
  3. $p->length(...) turns the method into a closure to call later.
  4. strtoupper(...) hands a named function straight to array_map.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 3 in Modern touches, step 24 of 27 in Language basics.

← Previous Next →