Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static methods: are they still bad considering PHP 5.3 late static binding?

If you search on the reasons why static methods are bad the first thing you find it is because you can't override it when you are unit testing.

So is this still true considering in PHP 5.3 you can do whatever you want with the introduction of static::?

Add:

http://sebastian-bergmann.de/archives/883-Stubbing-and-Mocking-Static-Methods.html

Note he explains even how to use singleton without any testing problem:

  • http://sebastian-bergmann.de/archives/882-Testing-Code-That-Uses-Singletons.html
like image 396
dynamic Avatar asked May 17 '11 19:05

dynamic


2 Answers

If you have a static member function, it could usually be a free function. The usual reaction is then that the coder has opted for a static member function only because of the myth that "everything must be in an object".

That's why people discourage them.

And, because it's not a very convincing argument, those people pointed to unit testing instead. Not sure what they'll do now.

like image 150
Lightness Races in Orbit Avatar answered Oct 06 '22 00:10

Lightness Races in Orbit


Static methods aren't bad in themselves. Sometimes certain operations don't make sense to require a particular object to do. For example, a function like square root would make more sense being static.

Math::sqrRoot(5);

rather than having to instantiate a Math 'object' and then call the function.

$math = new Math();
$result = $math->sqrRoot(5);
like image 43
Lotus Notes Avatar answered Oct 05 '22 22:10

Lotus Notes