Static Functions / Classes.. Reasonsing? [duplicate]
Possible Duplicate:
When should I use static methods in a class and what are the benefits?
I'm working in PHP right now.
I'm working on two groups of Functions.
I have a class which consists of Date Handling Functions.
In this class I have no need for properties as each function/method is more or less a utility. As such I have made my class' functions all static.
I have a couple questions from here.
1) What benefits are there from using Static methods? I understand that there is lower processing overhead because there is not an Object. I've also heard this is negligible (depending).
2) What other types of functions/methods would be good candid开发者_JS百科ates for "static" besides utilities?
Thanks
The key concept of using static methods is that they are bound to a class, not an instance of the class. A good guideline is that **anything requiring state is not suitable to being used statically*.
Utility methods are definitely a good candidate for static usage, as they are often short and require no state. Some other guidelines might be:
- Input and output are not reliant on anything except each other.
- The method has no context, that is, it doesn't make sense to associate it with an instance of an object.
- A method/variable requires no differentiation between objects, and a single declaration is all that is required. This applies mostly to static class variables, such as a counter that is shared across all instantiated objects.
精彩评论