Use cases for anonymous classes

PHP 7 is becoming more and more adopted among developers, and we now enjoy using scalar and return type declarations, null coalescing operator, new error handling and other cool features that we were eagerly waiting for. There are already many articles that provide practical examples for using all these new features, but one of them didn't seem to get enough attention. It's a anonymous classes feature that is in question.

The shortest possible explanation of a feature is that anonymous classes can be used for creating one-off objects, as a convenient alternative over full class definitions. I won't go further with defining anonymous classes, because the aim of this blog post is to show you a practical example of using them. More detailed explanation can be found in the official documentation.

Write Test Doubles like a champ

While working on a second version of my Disqus Helper library, in an effort to make it full-fledged PHP 7 library, I spontaneously came to a valid use-case for anonymous classes. Namely, it happened while writing tests for WidgetManager component, where I needed to verify that the exception is raised in case of an invalid widget implementation.

I was lazy enough to create a Test Double, so I decided to give it a try with defining invalid Widget on-the-fly:

public function testExceptionIsRaisedInCaseOfGettingInvalidWidget()
{
    $this->expectException(InvalidWidgetException::class);
    $this->expectExceptionMessage(sprintf(
        "Widget must implement %s interface",
        WidgetInterface::class
    ));

    $widgetManager = WidgetManager::create([
        'myWidget' => function () {
            return new class
            {
                public function getScriptName()
                {
                    return 'test.js';
                }
                public function render(array $options = [])
                {
                    return '<div id="my_widget"></div>';
                }
            };
        }
    ]);

    $widgetManager->get('myWidget');
}

How cool is that? Laziness apparently sometimes worth it, but joking aside, I think that in this particular case, anonymous class approach is more correct and more meaningful than having a full class definition of a dummy object.

Anything else?

While testing is probably the most obvious case for using anonymous classes, as they are perfect alternative for messing with complex mocking APIs, you should be aware of certain advantages that anonymous classes provide.

In terms of performance, by creating anonymous classes for some trivial implementations, you essentially avoid hitting the autoloader.

Also, the very nature of one-off objects prevents them from being used outside the scope they are defined in, which may affect some encapsulation-related considerations.

Final thoughts

I guess we all remember that agony in pre-PHP 5.3 era whenever you needed to supply a callable to some PHP function, for example array_filter or preg_replace_callback. Programming without anonymous function and closures is almost unthinkable nowadays. Hopefully, the same bright future is ahead of anonymous classes, too.


anonymous classes testing test double