介绍
在编程中,范围是指变量可访问的程度。通常,简单的PHP脚本(没有任何结构,如循环,函数等)只有一个作用域,从定义的角度出发,整个程序都可以使用变量。
主脚本中的变量也可用于包含include或require语句的任何其他脚本。在以下示例中,test.php脚本包含在主脚本中。
这是主脚本
$var=100; include "test.php"; ?>
包含的文件test.script如下-
echo "value of of \$var in testscript.php : " . $var; ?>
执行主脚本时,显示以下结果
value of of $var in testscript.php : 100
但是,当脚本具有用户定义的功能时,内部的任何变量都具有局部作用域。结果,在函数内部定义的变量无法在外部访问。在函数外部(上方)定义的变量具有全局范围。
示例
<?php $var=100; //global variable function myfunction(){ $var1="Hello"; //local variable echo "var=$var var1=$var1" . "\n"; } myfunction(); echo "var=$var var1=$var1" . "\n"; ?>
输出结果
这将产生以下结果-
var= var1=Hello var=100 var1= PHP Notice: Undefined variable: var in line 5 PHP Notice: Undefined variable: var1 in line 8
请注意,全局变量在局部函数范围内不会自动可用。另外,内部变量不能在外部访问
全局关键字
应该使用global关键字显式启用对本地范围内的全局变量的访问。PHP脚本如下-
示例
<?php $a=10; $b=20; echo "before function call a = $a b = $b" . "\n"; function myfunction(){ global $a, $b; $c=($a+$b)/2; echo "inside function a = $a b = $b c = $c" . "\n"; $a=$a+10; } myfunction(); echo "after function a = $a b = $b c = $c"; ?>
输出结果
这将产生以下结果-
before function call a = 10 b = 20 inside function a = 10 b = 20 c = 15 PHP Notice: Undefined variable: c in line 13 after function a = 20 b = 20 c =
现在可以在函数内部处理全局变量。此外,对函数内部的全局变量所做的更改将反映在全局命名空间中
$GLOBALS数组
PHP将所有全局变量存储在名为$GLOBALS的关联数组中。变量的名称和值构成键值对
在以下PHP脚本中,$GLOBALS数组用于访问全局变量-
示例
<?php $a=10; $b=20; echo "before function call a = $a b = $b" . "\n"; function myfunction(){ $c=($GLOBALS['a']+$GLOBALS['b'])/2; echo "c = $c" . "\n"; $GLOBALS['a']+=10; } myfunction(); echo "after function a = $a b = $b c = $c"; ?>
输出结果
before function call a = 10 b = 20 c = 15 PHP Notice: Undefined variable: c line 12 Notice: Undefined variable: c in line 12 after function a = 20 b = 20 c =
静态变量
使用static关键字定义的变量不会在每次调用该函数时初始化。此外,它保留了先前通话的值
示例
<?php function myfunction(){ static $x=0; echo "x = $x" . "\n"; $x++; } for ($i=1; $i<=3; $i++){ echo "call to function :$i : "; myfunction(); } ?>
输出结果
这将产生以下结果
call to function :1 : x = 0 call to function :2 : x = 1 call to function :3 : x = 2