* There are only three scopes:
* 1. Global: Created outside the function, only used in the current script except for the function;
* 2. Local: Created inside the function, can only be used in the function, not accessible externally;
* 3. Static: Created inside the function, only used in the function, its value will not be lost after the function is executed;
$siteName = 'PHP中文网'; //全局变量
//The global variable automatically becomes a key-value pair in the global variable array, and the key corresponds to the variable
$GLOBALS['siteName']='PHP中文网'; //全局变量替代语法
* Function: It is a code segment with a specific function in the script, which can be called repeatedly
* 1. Basic syntax:
* 1.1 Function declaration: function funcnName($args){ #code...}
* 1.2 Function expression: $funcName = function ( $ages){ #code...}
* 2. Call:
* 2.1 Call by name: funcName($args) / $funcName($args)
* 2.2 Self-calling: declaration and calling are completed at the same time
* (function (args){ #code...})()
function hello() { global $siteName; //引用全局变量,使用全局变量数组,不必声明引入 $userName = 'Peter Zhu'; //局部变量 // return '欢迎来到'.$siteName.',我是:'.$userName; return '欢迎来到'.$GLOBALS['siteName'].',我是:'.$userName; } echo hello(); //函数调用 echo '<hr color="red">';
//Static variables must and can only be used in Declared and used in the function
function myStatic() { static $num = 1; //$num++,先将$num值输出后再加1 return '第'.$num.'次输出'.$num++.'<br>'; } echo '第一次执行完成后$num值:'.myStatic().'<br>';
//After the first execution is completed, the value of $num is 2
echo '第一次执行完成后$num值:'.myStatic().'<br>';
//After the second execution is completed, $ The num value is 3
echo '第一次执行完成后$num值:'.myStatic().'<br>';
//After the third execution, the $num value is 4
echo '第一次执行完成后$num值:'.myStatic().'<br>';
* Super global variables: $_SERVER, $_COOKIE, $_SESSION, $_GET, $_POST ,$_REQUEST
* 1. They are predefined variables, all are arrays, and can be used as they come, no declaration is required;
* 2. Cross-scope, both globally and locally (inside the function) ) can be used directly;
* 3. Cross-scope is not cross-script. The so-called super global, including global, refers to the current script file.
echo '<hr color="blue">';
//Can be referenced directly globally
echo '我的姓名是:'.$_GET['name'];
//Can also be referenced directly in the function
function sayName() { //超全局变量不需要使用关键字 global 进行声明 return '我的姓名是:'.$_GET['name']; }
//Call the function
echo sayName();