Home >Backend Development >PHP Problem >What is the meaning of php global variables
In PHP, global variables are variables defined outside the function and can be referenced and changed anywhere. When using global variables in a PHP function, you can use the "global" keyword to declare the used content.
The operating environment of this article: Windows 10 system, PHP version 7.1, Dell G3 computer.
php variables can be roughly divided into global variables and local variables. The simple difference is that local variables are defined in functions and can only be used in functions. Global variables Variables are defined outside the function and can be referenced and changed anywhere.
Definition method: global $variable
Explanation: $variable is the variable name, global is the type of the global variable
Example: Define a global variable and output it in the function This variable:
$variable="hello baidu!"; print_result(); function print_result(){ global $variable; echo $variable; }
If the definition is successful, the final result will be hello baidu!
The definition and use of global variables
$name = "why"; function changeName(){ $name = "what"; } changeName(); echo "my name is " . $name . " "; ?>
The result of executing the code is: my name is why, instead of what is displayed after executing changeName(). Analyzing the reason, this is because the $name variable in the function body changeName is set to a local variable by default, and the scope of $name is within changeName. So, modify the code and add global variables as follows:
global $name; $name = "why"; function changeName(){ $name = "what"; } changeName(); echo "my name is " . $name . " "; ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of What is the meaning of php global variables. For more information, please follow other related articles on the PHP Chinese website!