global关键字
<?php
$x=5;
$y=10;
function myTest() {
global $x,$y;
$y=$x+$y;
}
myTest();
echo $y; // 输出 15
?>
函数内部变量前面使用global关键字,可以访问全局变量。
$GLOBALS[index]
这里存储了所有的全局变量,使用下标变量名进行访问,并且能够直接更新全局变量。
<?php
$x=5;
$y=10;
function myTest() {
$GLOBALS['y']=$GLOBALS['x']+$GLOBALS['y'];
}
myTest();
echo $y; // 输出 15
?>
static
<?php
function myTest() {
static $x=0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>