Anonymous classes in PHP 7

Eligijus picture Eligijus · Jul 15, 2015 · Viewed 15.5k times · Source

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"; }});

Answer

marcosh picture marcosh · Jul 15, 2015

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