local | 局部作用域 |
global | 全局作用域 |
static | 静态作用域 |
parameter | 函数参数作用域 |
局部变量 local
在函数内部声明的变量为局部变量,仅能在函数内部访问
function hello(){
$hi = "hi";
echo $hi;
}
hello();
全局变量 global
在函数外部声明的变量为全局变量,除了在函数内, 它能被脚本的任何部分访问。若想在函数内访问全局变量,需要使用global关键字声明
$a = 1;
function hello(){
echo $a;
}
hello();
//出现Notice级报错,无输出
function hi(){
global $a; //使用global关键字声明
echo $a;
}
hi();
//输出 1
静态变量 static
函数执行完毕后,函数内的局部变量均会被删除。若要一直保持局部变量存在不被删除,则需要在第一次声明变量时使用static关键字
function hello(){
$a=0;
$a++;
echo $a;
}
hello();
hello();
//输出 11
function hi(){
static $a=0;
$a++;
echo $a;
}
hi();
hi();
//输出 12
参数 parameter
参数是通过代码把值传递给函数的局部变量
$a = 10;
function hello($value){
echo $value;
}
hello($a);
//输出10