Home  >  Article  >  Backend Development  >  How to define global variables in php

How to define global variables in php

(*-*)浩
(*-*)浩Original
2019-09-20 14:34:0520090browse

php global variables can be defined with global. It is wrong to define global outside. It must be declared within the function.

How to define global variables in php

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

";
?>

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:

";
?>

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn