When do I use static variables/functions in php?

前端 未结 8 1015
天涯浪人
天涯浪人 2020-11-30 20:32

I am refreshing myself on OOP with PHP and I saw an example of setting functions and/or variables as static. When and why would I set a variable/function to static? I\'ve

相关标签:
8条回答
  • 2020-11-30 21:22

    Here's a random, though fairly good description of the differences between static and instance methods.

    From the post:

    Instance methods are instance methods because they rely on the state of the specific object instance. Instance methods are tied to a particular instance because the behavior that the method invokes relies upon the state of that particular instance.

    When you declare a method as static, you define that method as being a class method. A class method applies to the class as opposed to any particular instance. The behavior instigated by a class method does not rely on the state of a particular instance. In fact, a static method cannot rely on an instance's state since static methods lack access to this reference. Instead, the behavior of a class method either depends on a state that all objects share at the class level, or is independent of any state at all.

    If a method relies on an object instance's state it should be an instance methods. If a method is general for all or no instances of a class, and does not rely on the object state, it should be a static method. Instance methods are most commonly used. However static methods are very useful for utility and factory classes amogst many other uses.

    0 讨论(0)
  • 2020-11-30 21:24

    Visit: http://verraes.net/2014/06/when-to-use-static-methods-in-php/

    Static methods are nothing more than namespaced global functions. Namespacing, I think we can all agree on, is great. As for global functions: We use those all the time. The native functions in PHP form our basic building blocks.

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