What is the meaning of php global variables

WBOY
Release: 2023-03-15 12:58:01
Original
6512 people have browsed it

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.

What is the meaning of php global variables

The operating environment of this article: Windows 10 system, PHP version 7.1, Dell G3 computer.

What is the meaning of php global variables

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;
}
Copy after login

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 . "
";
?>
Copy after login

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 . "
";
?>
Copy after login

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!

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!