PHP 變數範圍

小傑
小傑
Jul 24, 2017 · 2 min read

區域變數 (local variable)

  • 在 function 中宣告
  • 只能在宣告的 function 中使用 (local scope)
  • 不同的 function 中可宣告相同名稱的區域變數
  • 在宣告變數 function 結束時,區域變數也就消滅了
  • 宣告時不需使用任何關鍵字 (keyword)

$myNum = 10; // 全域

function addTen($num){
$num += 10; //區域
}

全域變數 (global variable)

  • 在 function 外宣告
  • 除了 function 中的 script不能存取外,整個網頁中的 script 都可以存取該變數( global scope )
  • 若要在 function 中使用全域變數,需使用關鍵字 global,見下例
  • 在網頁關閉時,全域變數消滅

function addFive($num){
global $myNum; //在函數裡使用全域變數
$myNum += 15;
}

addFive($myNum);

echo $myNum; //值為25,因為使用global關鍵字,得以改變全域變數。

addTen($myNum);

echo $myNum; //值也為25,addTen的區域變數並不會影響到全域變數。

參考來源:PHP 四種變數範圍比較:區域、全域、靜態、參數

gensou

PHP Beginner

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade