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"; }});
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"; }});
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());
}
As Rasmus Lerdorf said at WeAreDevelopers See website, when he was talking about new features in PHP7:
(Watch it on YouTube)
Anonymous classes, just like anonymous functions; basically you can spin up classes on-the-fly and throw them away. Personally, I've never had a use for this, but there are framework folks that say that this is important. I'm still a little bit dubious, but it was easy to implement; and people smarter than me have said "Yeah, yeah, it's useful"! OK!
Edit
Considering the quotation above by Mr. Lerdorf, anonymous classes doesn't mean to be really useless.
As an example, it's good for some sort of Singleton patterns, by defining and instantiating the class at the same time.
Or, another example is implementing nested classes with it. See this.
Good case I can provide is to provide context specific listener to use it only once or an adapter for external listener, without defining custom class. Here is an example:
$this-apiCaller->call('api_name', $parameters, new class($businessListener) implements ApiListenerInterface
{
private $listener;
public function __construct($originalListener)
{
$this->listener = $originalListener;
}
public function onSuccess($result)
{
$this->listener->addLog(new SuccessRecord($result));
}
public function onFailure($error)
{
$this->listener->addLog(new ErrorRecord($error));
}
});
Anonymous classes are not different than regular classes in PHP except they need to be created and instantiated at the same time.That means they can be extended from others classes, can use interfaces etc.
If you think you need a very simple class and never use it again in anywhere else, it is right for you. Another reason could be that you need a simple class (with multiple simple methods) and you don't want to spend time for documentation so you create one on the go to achieve your task.
© 2022 - 2024 — McMap. All rights reserved.