tags:

views:

858

answers:

5

Doing some code reviews lately I came across a number of classes that have significant number of static methods in them... and I can't seem to grasp why? Hence my question:

What are the best practices regarding using static methods in PHP?

When would one want to use them and when would one shouldn't use them?

What are specific difference in how runtime handles static methods? Do they affect performance or memory footprint?

A: 

You don't need to create an instance of the class to use its static methods.

Havenard
A: 

Static methods are used for

  • functions that are related to the whole collection of objects of the given class (e.g. singleton pattern)
  • functions that are not related to anything, but must be put under a class because of OO (e.g. utility classes)
Zed
A: 

Static method doesn't require an instance (and may return one instead) and is more or less like a global function except for it is put in class' namespace (and therefore avoid collisions with other functions) and has access to class' private members.

So, use it whenever you're interested in these properties of the function.

Michael Krelin - hacker
A: 

There is nothing PHP specific about the use of static methods.

Static methods can be called directly on the class - no need for an instantiated object.

So their main use is for methods that are related to the classes functionality, but do not need an existing instance to be of use for other code.

A common example would be a custom comparison method that can be passed to, say, the uasort() function to sort an array of objects of the class' type.

Henrik Opel
+5  A: 

Doing some code reviews lately I came across a number of classes that have significant number of static methods in them... and I can't seem to grasp why

PHP didn't have namespaces before 5.3, so all function/variables would be in global scope unless they belonged in some class. Putting them in a class as static members is a workaround for not having namespaces (and that's probably why you saw them in "significant" number)

Generally, they are used for functions that aren't much useful in individual objects, but has some use at class level (as said in other answers)

Imran