首页 > 文章列表 > PHP变量作用域

PHP变量作用域

php变量 作用域 变量作用域
436 2023-09-07

简介

在编程中,作用域是指变量可访问的范围。一般来说,一个简单的 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

请注意,全局变量在函数的局部范围内不会自动可用。此外,函数内部的变量在外部不可访问

全局关键字

应使用全局关键字显式启用对本地范围内的全局变量的访问。 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();
}
?>

输出

This will produce following result

call to function :1 : x = 0
call to function :2 : x = 1
call to function :3 : x = 2