PHP 变量作用域
phpserver side programmingprogramming更新于 2025/8/19 7:37:17
简介
在编程中,作用域是指变量可访问的范围。通常,一个简单的 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" . "
";
}
myfunction();
echo "var=$var var1=$var1" . "
";
?>
输出
这将产生以下结果 −
var= var1=Hello var=100 var1= PHP Notice: Undefined variable: var in line 5 PHP Notice: Undefined variable: var1 in line 8
请注意,全局变量在函数的局部作用域内不会自动可用。此外,函数内部的变量在函数外部无法访问。
global 关键字
在局部作用域内访问全局变量需要使用 global 关键字明确启用。PHP 脚本如下−
示例
<?php $a=10; $b=20; echo "before function call a = $a b = $b" . "
"; function myfunction(){ global $a, $b; $c=($a+$b)/2; echo "inside function a = $a b = $b c = $c" . "
"; $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" . "
"; function myfunction(){ $c=($GLOBALS['a']+$GLOBALS['b'])/2; echo "c = $c" . "
"; $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" . "
";
$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

