Interview frequency: …
Short answer
They are classes created and instantiated inline without a formal name, useful in tests for creating mock objects or quickly implementing single-use interfaces.
Explanation
Anonymous Classes were added in PHP 7 to avoid creating new class files when an object is needed only in one specific context. An anonymous class can receive constructor parameters, implement interfaces, and extend classes, while retaining all the features of a regular class.
Code example
$logger = new class implements LoggerInterface {
public function log(string $msg): void {
echo $msg;
}
};Common mistakes
- Using anonymous classes for objects that need to be stored in sessions or serialized.
Follow-up questions
- What are Readonly Classes in PHP 8.2, and how do they support immutable Value Objects?
- When should you choose an Interface versus an Abstract Class in PHP code design?