Alex Rivera | Logout

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

Asked 2010-01-17T06:10:45.450
72

I have concept of static variables but what are the benefits of static methods in a class. I have worked on some projects but I did not make a method static. Whenever I need to call a method of a class, I create an object of that class and call the desired method.

Q: Static variable in a method holds it's value even when method is executed but accessible only in its containing method but what is the best definition of static method?

Q: Is calling the static method without creating object of that class is the only benefit of static method?

Q: What is the accessible range for static method?

Thanks

Edit
Report

2 Answers

12

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.

answered 2010-01-20T12:18:43.410
2

One common usage of static methods is in the named constructor idiom. See: http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.8.

answered 2010-01-17T06:17:42.687

Your Answer