Anonymous classes in PHP 7
Asked Answered
W

5

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"; }});
Whereas answered 15/7, 2015 at 14:39 Comment(2)
anonymous classes (called inner classes in Java) have been around for quite a while and you can read about them in many places. I recommend you come back here when you have a more specific question.Barter
@Barter An inner class is different than an anonymous class.Bomar
M
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
Mobile answered 15/7, 2015 at 20:10 Comment(0)
M
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());
}
Mimicry answered 1/4, 2020 at 9:32 Comment(0)
R
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.

Rana answered 10/9, 2018 at 15:25 Comment(0)
L
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));
    }
});
Lenssen answered 30/5, 2017 at 18:46 Comment(0)
G
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.

Gearwheel answered 4/12, 2016 at 3:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.