How to define global variables in php

(*-*)浩
Release: 2023-02-24 14:40:01
Original
20277 people have browsed it

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

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/>";
?>
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:

<?php
global $name;
$name = "why";
function changeName(){
    $name = "what";
}
changeName();
echo "my name is " . $name . "<br/>";
?>
Copy after login

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!

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