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();
?>