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"; }});
Anonymous classes ¶ Anonymous classes are useful when simple, one-off objects need to be created. All objects created by the same anonymous class declaration are instances of that very class. Note: Note that anonymous classes are assigned a name by the engine, as demonstrated in the following example.
In PHP, an anonymous class is a useful way to implement a class without defining it. These are available from PHP 5.3 onwards. Anonymous classes are useful because: They are not associated with a name.
An anonymous class cannot access local variables in its enclosing scope that are not declared as final or effectively final. Like a nested class, a declaration of a type (such as a variable) in an anonymous class shadows any other declarations in the enclosing scope that have the same name.
PHP Classes and Objects Anonymous Classes Anonymous classes were introduced into PHP 7 to enable for quick one-off objects to be easily created. They can take constructor arguments, extend other classes, implement interfaces, and use traits just like normal classes can.
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:
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()); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With