PHP變量關鍵字global/$GLOBAL[]/static

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

?>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章