Search code examples
phpanonymous-classphp-7

Anonymous classes in PHP 7


Where can i use and should i use anonymous classes that are presented in PHP 7 ? I can't find a use case for them.

$message = (new class() implements Message {
public function getText() { return "Message"; }});

Solution

  • You can find the information you are looking for here, where the RFC is presented.

    The key points of the section "Use cases" are the following:

    • Mocking tests becomes easy as pie. Create on-the-fly implementations for interfaces, avoiding using complex mocking APIs.
    • Keep usage of these classes outside the scope they are defined in
    • Avoid hitting the autoloader for trivial implementations