One of the most recent new features of PHP is Anonymous Classes, introduced with PHP version 7.
But what are Anonymous Classes? How do you use them? And what would you use them for? Let’s take a look behind the mask, and find out.

Anonymous Classes were introduced to PHP7 with very little fanfare, and without much explanation of the use cases where they might have value. Yet they have the potential to be extremely useful in a whole range of situations from internal classes within libraries, to creating mocks for unit testing; but only if developers are aware of them, and understand how to use them, and what limitations there are to using them.

A central part of this talk will look at how Anonymous Classes can be used as an alternative to stubs and mocks in unit testing, and how assertions like

$myMock->expects($this->once())->method('blah')->with($param2, $param2)
can be simulated; and how to use Anonymous classes to unit test abstract classes and traits.

Another part will include my investigations into an Anonymous Class Factory with additional information about creating Inner/Nested Anonymous classes.

Comments

Comments are closed.

It seems that presentation was more about implementing mocking lib than anonymous classes itself. I would make more simpler examples.

Interesting. Looking forward for the phpanpy framework.

Leon Boot at 12:12 on 29 Jan 2018

Prior to the talk I couldn't come up with why anonymous classes add anything useful, I was surprised to stand corrected! Although I wouldn't agree on all usecases (I felt that the use case for the first example, with the locations, could be solved much simpler, and I think that private methods shouldn't be tested just because you can now) there's still plenty of situations where anonymous classes are a valid addition to the toolkit. Thanks for the insights!

Leon Boot at 12:12 on 29 Jan 2018

Oh, and cats. It really needs cats.

Jasper Kennis at 14:58 on 29 Jan 2018

Too complicated for me. But inspiring.

Nice examples of how to apply anonymous classes, can relate to a few of them. I found it to be a little bit monotonic though, perhaps it needs a bit more quirky examples and some fun :)

Anonymous at 09:20 on 30 Jan 2018

Interesting use-case to use anonymous classes for private method testing.