Anonymous Classes

An anonymous class is a class with no name, declared and instantiated in one expression with new class { … }. It is handy for a small, one-off object that does not need to be reused or referenced by a class name elsewhere. Like a named class, it can accept constructor arguments and implement an interface.

<?php
interface Greeter {
  function greet(): string;
}

$greeter = new class('Bob') implements Greeter {
  public function __construct(private string $name) {
  }
  public function greet(): string {
    return "Hello, {$this->name}!";
  }
};

echo $greeter->greet(), "\n";
var_dump($greeter instanceof Greeter);
?>

Hello, Bob! bool(true)
Since PHP 8.3, an anonymous class may also be declared readonly, exactly like a named class (see Readonly Properties and Classes). Every property then becomes write-once, and modifying one afterwards throws an \Error.

<?php
$point = new readonly class(3, 4) {
  public function __construct(public float $x, public float $y) {
  }
};

echo "{$point->x}, {$point->y}\n";

try {
  $point->x = 10;
} catch (\Error $e) {
  echo $e->getMessage(), "\n";
}
?>

3, 4 Cannot modify readonly property class@anonymous::$x