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

前端 未结 10 1316
孤独总比滥情好
孤独总比滥情好 2020-11-27 12:34

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

相关标签:
10条回答
  • 2020-11-27 12:56

    The only time you want to use a static method in a class is when a given method does not require an instance of a class to be created. This could be when trying to return a shared data source (eg a Singleton) or performing an operation that doesn't modify the internal state of the object (String.format for example).

    This wikipedia entry explains static methods pretty well: http://en.wikipedia.org/wiki/Method_(computer_science)#Static_methods

    0 讨论(0)
  • 2020-11-27 12:56

    Static Methods in PHP:

    Can be called without creating a class object.

    Can only call on static methods and function.

    0 讨论(0)
  • 2020-11-27 12:59

    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.

    0 讨论(0)
  • 2020-11-27 13:03

    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.

    0 讨论(0)
  • 2020-11-27 13:06

    Static variables and static methods are bound to the class, and not an instance of the class.

    Static methods should not contain a "state". Anything related to a state, should be bound to an instantiated object, and not the class.

    0 讨论(0)
  • 2020-11-27 13:08

    static elements are accessible from any context (i.e. anywhere in your script), so you can access these methods without needing to pass an instance of the class from object to object.

    Static elements are available in every instance of a class, so you can set values that you want to be available to all members of a type.

    for further reading a link!

    0 讨论(0)
提交回复
热议问题