Home > Article > Backend Development > How to define global variables in php
php global variables can be defined with global. It is wrong to define global outside. It must be declared within the function.
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 the variable in the function: (Recommended learning: PHP programming from entry to proficiency)
$variable="hello baidu!"; print_result(); function print_result(){ global $variable; echo $variable; }
If the definition is successful, the final result will be output hello baidu!
The definition and use of global variables
<?php $name = "why"; function changeName(){ $name = "what"; } changeName(); echo "my name is " . $name . "<br/>"; ?>
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:
<?php global $name; $name = "why"; function changeName(){ $name = "what"; } changeName(); echo "my name is " . $name . "<br/>"; ?>
The above is the detailed content of How to define global variables in php. For more information, please follow other related articles on the PHP Chinese website!