Home >Backend Development >PHP Tutorial >Variable generation and scope in PHP_PHP tutorial
In PHP, you do not need to notify PHP before using a variable. The place where a variable is used for the first time determines the scope of the variable. In some programming languages such as C, global variables are visible inside the function. This is not the case in PHP. When creating a function in PHP, you must explicitly declare the global variables to be used using glob.
For example:
function printcity($cityname)
{
print("Your favorite city is: $cityname");
}
$city ="Beijing";
function citya() //Define a function
{
$city="Guangzhou";
printcity($city);
}
function cityb( )
{
$city="Shenzhen";
printcity($city);
}
function cityc()
{
global $city; // Get a reputation Global variable
printcity($city);
}
citya();//Output Guangzhou
cityb();//Output Shenzhen
cityc();//Output Beijing
?>
Note:
The variables inside the function are only valid when the function is used. Once the function ends, all variables of the function will be cleared.