It’s been seven years since Kore Nordmann first published “static considered harmful” on his blog, explaining the problems with using static method calls in classes, and the difficulties that they cause when trying to test that class. Seven years on, and those difficulties are still the same, and there is still new code being written using static calls despite that knowledge; but it’s often a more severe problem in legacy code with little or no unit tests.a
So why exactly are static calls so bad? If you’ve read Kore’s article, then you probably have a good idea already; but what that article doesn’t cover is approaches that we can use to make the code testable.
He covers the main issue static methods have when it comes to testing: they introduce coupling by hard-coding a dependency into your code. He talks about the static testing functionality that various PHP testing tools provided: PHPUnit, Phake and Mockery. He then focuses on a newer tool that he’s discovered to help make the testing simpler: AspectMock. He gives an example of it in use and some examples of tests using anonymous classes to make it easier to create tests on the fly.