A scope is one in which a variable can be used or visible in a script. PHP has 6 fundamental scoping rules.
1. Built-in super global variables can be used and visible anywhere in the script. For example:
<?php
Print_r ($_server[' http_host ');//$_server[' Http_host '] is a super global variable with a value of localhost
function Test () {
echo $_server[' http_host '];//output localhost, indicating that the super global variable is visible in the function and does not need to be declared in advance
}
Test ();
echo $_server[' http_host '];//output localhost, indicating that the super global variable is visible outside the function
?>
2. Constants, once declared, can be visible globally, that is, they can be used inside and outside the function.
<?php
Define (' USERNAME ', "root")//declaring constant, constant name to enclose in quotation marks
function Test () {
echo username;//output root, indicating that the constants are visible in the function
}
Test ();
echo username;//output root, indicating that the constants are visible outside the function
?>
3. Global variables declared in a script are visible throughout the script, but not inside the function.
<?php
$num = 100;
function Test () {
echo $num//error, undefined variable $num; notice:undefined Variable:num in E:\app\phpstudy\WWW\test\index.php on line 4
}
Test ();
Echo $num;
?>
4. Variables used inside the function are declared as global variables, and their names are consistent with the global variable name.
<?php
$num = 100;
function Test () {
Global $num;//To use the keyword global
echo $num;//Output 100
}
Test ();
echo $num;//Output 100
?>
<?php
$num = 100;
function Test () {
Global $num;//To use the keyword global
$num = 200;
echo $num;//Output 200
}
Test ();
echo $num//Output 200, the value of the global variable is modified in the function
?>
5. A variable created inside a function and declared as static cannot be visible outside of the function, but it can be persisted during the colorful execution of a function.
<?php
function Test () {
The static variables defined in the function are part of this function.
static $static _num = 1;
$static _num++;
echo $static _num;
}
Test ();//Output 2
Test ();//Output 3
The echo $static the static variable defined in the _NUM;//function is not visible outside the function, and the error is here
?>
6. A variable created inside a function is local to the function, and the variable does not exist when the function terminates.