When should I use static methods in a class and what are the benefits?

Solution 1:

Your description of a static variable is more fitting to that found in C. The concept of a static variable in Object Oriented terms is conceptually different. I'm drawing from Java experience here. Static methods and fields are useful when they conceptually don't belong to an instance of something.

Consider a Math class that contains some common values like Pi or e, and some useful functions like sin and cos. It really does not make sense to create separate instances to use this kind of functionality, thus they are better as statics:

// This makes little sense
Math m = new Math();
float answer = m.sin(45);

// This would make more sense
float answer = Math.sin(45);

In OO languages (again, from a Java perspective) functions, or better known as methods, cannot have static local variables. Only classes can have static members, which as I've said, resemble little compared to the idea of static in C.

Solution 2:

Static methods don't pass a "this" pointer to an object, so they can't reference non-static variables or methods, but may consequently be more efficient at runtime (fewer parameters and no overhead to create and destroy an object).

They can be used to group cohesive methods into a single class, or to act upon objects of their class, such as in the factory pattern.

Solution 3:

Syntax (php) for static methods:

<?php
class Number {
    public static function multiply($a, $b) {
        return $a * $b;
    }
}
?>

Client code:

echo Number::multiply(1, 2);

Which makes more sense than:

$number = new Number();
echo $number->multiply(1, 2);

As the multiply() method does not use any class variables and as such does not require an instance of Number.