What it is and why to use it
Sometimes an operation needs an object with a small interface implementation that will not be reused elsewhere. An anonymous class lets you declare and instantiate it in one expression. It has ordinary methods, properties and a constructor, but no source-level name that you need to invent and maintain.
How it works
Write new class followed by optional constructor arguments and the class body. It can extend one parent and implement interfaces just like a named class. Unlike closures, an anonymous class does not automatically capture surrounding variables; pass required data into its constructor. Use a named class when the implementation grows or needs to be reused, documented or configured independently.
Common mistakes and limitations
Do not depend on the generated internal class name, which is not a stable application identifier. Do not assume that nesting the declaration inside another object grants access to that object’s private members. An anonymous implementation should still satisfy the same contracts as any named implementation.
Run the examples locally
Save each complete example in its own example.php file and run php example.php in a terminal from that folder. Each example is independent: do not paste both into one file, especially when they declare classes with the same names. Output appears in the terminal. The examples use PHP 8.0-compatible syntax; use a currently supported PHP release for development.
The <?php opening tag starts PHP code. declare(strict_types=1) requests strict scalar argument checks for function calls made from this file; it does not validate external input for you. echo writes output, and PHP_EOL adds the platform’s line ending. Quotation marks delimit strings; they are not part of the printed text unless explicitly included in the string.
These examples use built-in PHP language features and standard extensions. They need no Composer packages, database server, browser APIs or network access. Codectionary’s PHP preview does not execute PHP; use your local interpreter to reproduce the output.
Check your interpreter, lint and run one saved example
php -v
php -l example.php
php example.phpContinue learning
Use the related guides to connect this operation to the surrounding language features. Practise by changing the example inputs and predicting the output before running it.
Syntax
$handler = new class implements Handler { /* methods */ };Examples
Provide a local message sink
Implement an interface in place for a small command-line demonstration.
<?php
declare(strict_types=1);
interface MessageSink {
public function write(string $message): void;
}
$sink = new class implements MessageSink {
public function write(string $message): void {
echo 'Notice: ', $message, PHP_EOL;
}
};
$sink->write('Lesson saved');
- MessageSink describes the public write contract.
- new class creates an instance whose write method satisfies that contract immediately.
- The call prints a prefixed notice. Tests and small adapters can use the same pattern when a reusable named class would add little value.
- Expected output: Notice: Lesson saved
Pass a local value to the constructor
Give a one-off formatter its prefix explicitly.
<?php
declare(strict_types=1);
$prefix = 'PHP';
$formatter = new class($prefix) {
public function __construct(private string $prefix) {}
public function format(string $topic): string {
return $this->prefix . ': ' . $topic;
}
};
echo $formatter->format('Arrays'), PHP_EOL;
- The expression new class($prefix) forwards the outer value to the anonymous class constructor.
- Constructor promotion stores it in a private property for later method calls.
- format uses that stored property. The outer variable is not implicitly captured as it would be by an arrow function.
- Expected output: PHP: Arrays
Best practices
- Keep one-off implementations small and local.
- Pass dependencies explicitly instead of relying on hidden surrounding state.
Runtime & versions
PHP runtime on a server or CLI. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
PHP Manual