Anonymous classes in PHP 7

2019-02-06 00:48发布

问题:

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

回答1:

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


回答2:

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!



回答3:

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.



回答4:

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