Anonymous classes
Anonymous classes are useful when simple, one-off objects need to be created.
They can pass arguments through to their constructors, extend other classes,
implement interfaces, and use traits just like a normal class can:
Nesting an anonymous class within another class does not give it access to
any private or protected methods or properties of that outer class. In order
to use the outer class' protected properties or methods, the anonymous class
can extend the outer class. To use the private properties of
the outer class in the anonymous class, they must be passed through its
constructor:
All objects created by the same anonymous class declaration are instances of
that very class.
Note:
Note that anonymous classes are assigned a name by the engine, as
demonstrated in the following example. This name has to be regarded as an
implementation detail, which should not be relied upon.
Readonly anonymous classes
As of PHP 8.3.0, the readonly modifier can
be applied to anonymous classes.
Example #1 Defining a readonly anonymous class
<?php
// Using an anonymous class
var_dump(new readonly class('[DEBUG]') {
public function __construct(private string $prefix)
{
}
public function log($msg)
{
echo $this->prefix . ' ' . $msg;
}
});