Get the App
SLTechnology News&Howtos  ›  Network Security  › 

Static variable (static)

Shulou Source: shulou.com Published: 2022-06-01 04:25:23 10月06日 Update

I. static variables

In the above example, the local variable $an in the function is declared as a static variable using the static keyword, with an initial value of 0. 0. When the function is executed for the first time, the static variable $a changes from the initial value of 0 to 1. When the function is executed for the first time, the static variable $an is not released, but the result is saved in static memory. On the second execution, $a gets the result of the previous calculation from memory, continues the calculation, and stores the result 2 in the static memory space. Each time the function is executed in the future, the static variable will get the previous storage result from its own static memory space and calculate it as the initial value.

II. The use of the static keyword

Static members in a class are accessed directly using the class name instead of an object, in the following format:

Class name: static member property name; / / static member attribute can be accessed in this way both outside the class and in member methods

Class name: static member method (); / / static member method can be accessed in this way both outside the class and in member methods

In member methods declared in the class, you can also use the keyword "self" to access other static members. Because a static member belongs to a class, not to any object, it cannot be referenced with $this, and the self keyword provided to us in PHP is the keyword used to represent the class in the class's member methods. The format is as follows:

Self:: static member property name; / / use this way to access static member properties in this class in the member methods of the class

Self:: static member method name (); / / access static member methods in this class in this way in the member methods of the class

The result of the code running is 3 / 3

Tags: Static member method object variable function property class name key result run keyword memory mode output initial value first time member format space Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology Redmi Xiaomi Shulou Information Docker