Anonymous classes in PHP 7

倖福魔咒の 提交于 2019-11-29 02:59:29

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
MAChitgarha

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!

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!