Object-oriented – OO PHP static keyword, should I use it

object-orientedPHPstatic methodsstatic-keyword

I'm writing script for fb and I have 3 objects that I'll be using through all classes. I'm wondering if there is any advantage in using the static keyword except I don't have to create an instance every time I need to use a method/object? Which way should I go, with static or without it?

I know this is basic, but I'm new to OOP and I want to learn to use it in a proper manner.

Best Answer

Your question is a little vague so I'll try my best.

There's one good question to ask when you're trying to choose between creating a static or an instance method.

Do you need to persistent state between method calls?

Static methods are no different than traditional procedural functions. You give it an input and it should consistently product an output based on the input that is completely side-effect free.

Basically, you could use a traditional function declaration in it's place with no difference. The only benefit is that static methods are attached to a namespace where traditional functions are defined in the global namespace.

They don't matter so much in PHP because the language mixes both procedural and OOP styles but in languages that are pure OOP (ex C#/Java) there is no way to define functions so static methods are used in their place.

Static methods are perfectly acceptable to use when you're defining helper methods that act in a stateless manner. If you need data persistence between calls and/or find yourself relying on global variables, don't; use objects/instances instead.

Update:

Tom B made a very good point about unit testing. That static methods (like procedural functions) are inherently decoupled from the classes that they're attached to. So, if a static method fails, it may also cause any other instance method it's called in to also fail. It's a classic example of a side-effect.

That explains why I have encountered so many people parroting 'static methods are bad, mmmkay' in the TDD community. They have a completely valid point.

There are ways this could be improved. In the language, throwing an implicit exception when static methods fail. Technically, it wouldn't be any messier than doing type conversions. Assume it's going to break something if it fails. Of course, that assumes a higher degree of understanding to implement.

Either way, it comes down to the simple question.

Do you limit the language you use, or limit the ability to test your code's consistency?

My personal bias is toward expressiveness, the TDD school of thought's bias is toward consistency. YMMV.

I look forward to many years of religious wars over this topic.