When do I use static variables/functions in php?

前端 未结 8 1025
天涯浪人
天涯浪人 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:09

    Static elements have a number of characteristics that can be useful.

    1. First, they are available from anywhere in your script (assuming that you have access to the class). This means you can access functionality without needing to pass an instance of the class from object to object or, worse, storing an instance in a global variable.

    2. Second, a static property is available to every instance of a class, so you can set values that you want to be available to all members of a type.

    3. Finally, the fact that you don’t need an instance to access a static property or method can save you from instantiating an object purely to get at a simple function.

提交回复
热议问题