What Are Static Classes/Methods For?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

What Are Static Classes/Methods For?

Post by Jonah Bron »

I'm just wondering, what are static classes/methods actually for? The only application I can think of is a singleton. Otherwise, when is a good time for a static class?
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: What Are Static Classes/Methods For?

Post by John Cartwright »

Factories, registries, etc.

Basically, anytime you want to maintain a single instance of something (an object, array, etc) static is a likely candidate. It's generally best to avoid static's when possible, since they are harder to test, and remove the possibility of dependency injection, however, they are extremely useful as helper methods.
User avatar
Darhazer
DevNet Resident
Posts: 1011
Joined: Thu May 14, 2009 3:00 pm
Location: HellCity, Bulgaria

Re: What Are Static Classes/Methods For?

Post by Darhazer »

By definition, the static method, and the static members, belong to the class itself, and not to it's instance. The static methods have to be stateless - they should not depend on any previous calls to the method or to other static methods. You can have a static method if it fits in the above description and you want to provide it's functionality without need to have an instance of the object (if you will use the functionality only with the object's instance, there is no need to make the function static).
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: What Are Static Classes/Methods For?

Post by pickle »

I use static classes whenever I only ever need to do one thing with the class. An email sending class for example, or an error recording class.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply