Home > Article > Backend Development > The difference between adding the static keyword before variables and functions in PHP_PHP Tutorial
What is the difference between static global variables and ordinary global variables, static local variables and ordinary local variables, static functions and ordinary functions? The following article will answer you one by one.
(1) The description of global variables (external variables) is preceded by static to constitute a static global variable. Global variables themselves are static storage methods, and static global variables are of course also static storage methods. There is no difference between the two in the way they are stored. The difference between the two is that the scope of non-static global variables is the entire source program. When a source program consists of multiple source files, non-static global variables are valid in each source file. Static global variables limit their scope, that is, they are only valid within the source file in which the variable is defined, and cannot be used in other source files of the same source program. Since the scope of static global variables is limited to one source file and can only be shared by functions in that source file, errors can be avoided in other source files.
(2) From the above analysis, it can be seen that changing a local variable to a static variable changes its storage method and changes its lifetime. Changing a global variable to a static variable changes its scope and limits its scope of use.
(3) The scope of static functions is different from ordinary functions, only in this file. Functions used only in the current source file should be declared as internal functions (static), and internal functions should be described and defined in the current source file. Functions that can be used outside the current source file should be stated in a header file, and the source files that use these functions should include this header file.
In summary:
What is the difference between static global variables and ordinary global variables?
static global variables are only initialized once to prevent them from being referenced in other file units;
What is the difference between static local variables and ordinary local variables?
static local variables are only initialized once, and the next time will be based on the previous result value;
What is the difference between static functions and ordinary functions?
The static function has only one copy in the memory, and the ordinary function maintains a copy for each call;