Anonymous classes in PHP 7
I also found this useful when writing unit tests for traits so you can test only the trait method i.e.:
trait MyTrait
{
public method foo(): string
{
return 'foo';
}
}
...
public function setUp(): void
{
$this->testObject = (new class() {
use MyTrait;
});
}
public function testFoo(): void
{
$this->assertEquals('foo', $this->testObject->foo());
}
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