39

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"; }});
Fabian Schmengler
  • 24,155
  • 9
  • 79
  • 111
Eligijus
  • 634
  • 1
  • 6
  • 15
  • 1
    anonymous classes (called [inner classes in Java](https://www.google.com/webhp?ion=1&espv=2&es_th=1&ie=UTF-8#q=java%20inner%20classes&es_th=1)) have been around for quite a while and [you can read about them in many places](https://www.google.com/webhp?sourceid=ion=1&espv=2&es_th=1&ie=UTF-8#q=use+case+for+anonymous+classes). I recommend you [come back here when you have a more specific question](http://stackoverflow.com/help/how-to-ask). – morphatic Jul 15 '15 at 15:44
  • 7
    @morphatic An inner class is different than an anonymous class. –  Jul 25 '15 at 21:20

5 Answers5

43

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
yivi
  • 42,438
  • 18
  • 116
  • 138
marcosh
  • 8,780
  • 5
  • 44
  • 74
9

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());
}
WOpo
  • 121
  • 1
  • 8
5

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.

MAChitgarha
  • 3,728
  • 2
  • 33
  • 40
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));
    }
});
ryabenko-pro
  • 728
  • 1
  • 7
  • 18
0

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.

Mert Metin
  • 411
  • 1
  • 8
  • 21