PHP : global scope and local scope


PHP variable ေတြကို scope ခြဲထားႏိုင္ပါတယ္။ scope မတူညီတဲ႔ နာမည္တူ variable ႏွစ္ခုဟာ သီးျခား တည္ရွိတာျဖစ္ပါတယ္။ scope တစ္ခုထဲမွာဆိုရင္ေတာ႔ နာမည္တူ variable ႏွစ္လံုးတည္ေဆာက္ လုိ႔မရႏိုင္ပါဘူး။
example:
$var = '12';
echo $var;
အထက္ကေဖာ္ျပထားတဲ႔အတိုင္းဆိုရင္ $var ဟာ global scope ထဲမွာ ရွိေနတာပါ။ အဲဒါကို global variable လို႔လည္း ေခၚဆိုႏိုင္ပါတယ္။ေနာက္တစ္မ်ိဳးၾကည့္ရေအာင္
example
$var = '12';
function testFunction()
{
      $var = '13';

}
testFunction();
echo $var;
အထက္က ျပထားတဲ႔ code မွာ function တစ္ခု ပါ၀င္ျပီး အဲဒီ function ထဲမွာ အသံုးျပဳတဲ႔ variable ေတြဟာ အဲဒီ function ၇ဲ႕ local scope variable ေတြျဖစ္ပါတယ္။အျပင္ဘက္က $var ကေတာ႔ global scope ထဲမွာ တည္ရွိတာျဖစ္ပါတတယ္။ ဒါေၾကာင့္ function ထဲက $var='13' ဟာ function အျပင္ဘက္က $var ကို သက္ေရာက္မႈမရွိပါဘူး။ ဒါေၾကာင့္ အဲဒီ function ကို run ေအာင္လို႔ testFunction() ဆိုျပီး function call ေခၚျပီးမွ echo $var ကို ထုတ္ျပထားပါတယ္။ echo ၇ဲ႔ output အေနနဲ႔ 12 ပဲထြက္မွာျဖစ္ပါတယ္။ 13 မထြက္ပါဘူး။
ဆိုလိုတာက global scope နဲ႔ local scope ဟာ variable နာမည္တူေနရင္ေတာင္ သီးျခားတည္ရွိတဲ႔အတြက္ အထဲက တန္ဖိုးလည္း တူမေနႏိုင္ပါဘူး။
အကယ္၍ testFunction ကို ႏွစ္ခါ run ခိုင္းမယ္ဆိုရင္လည္း local scope ႏွစ္ခုျဖစ္လာပါတယ္။ 
example

function testFunction()
{
if(!isset($var))$var = 0; // to set initial value if $var is not exist.
$var++;
echo $var;
}
testFunction();
testFunction();
testFunction() ပထမတစ္ခါ မွာ 0 ကို တစ္တိုးျပီး 1 ျဖစ္လာမယ္။ ေနာက္တစ္ခါ ထပ္ testFunction() run ၇င္ အဲဒီ 1 ကို တစ္တိုးျပီး 2 ျဖစ္လာမယ္လို႔ ထင္စရာရွိပါတယ္။ဒါေပမယ့္ ျဖစ္ေပၚလာတယ့္ function ေတြရဲ႕ variable scope ေတြ မတူညီတဲ႔အတြက္ ဒုတိယ အၾကိမ္ $var ကို တစ္တိုးတာဟာ ပထမ run ထားတဲ႔ function ၇ဲ႔ $var ကို ၁ တိုးတာမဟုတ္ပါဘူး။ စမ္းၾကည့္ပါ။

ဒါဆို ရင္ global scope , local scope ေတြအေၾကာင့္ သိေလာက္ျပီထင္ပါတယ္။ ေနာက္ local scope ထဲမွာ global scope variable ကို ယူသံုးခ်င္တဲ႔အခါမွာ ဘယ္လိုသံုးႏိုင္သလဲဆိုတာေဖာ္ျပပါမယ္။
ဥပမာ function တစ္ခုထဲကေန အျပင္မွာရွိတဲ႔ variable ကို access ျပဳလုပ္လိုတဲ႔အခါမွာ သံုးလို႔ရပါတယ္။

example
$var = "hello";
function testFunction()
{
    global $var;
    echo $var." world";
}
အထက္က code ကိုၾကည့္ပါ။ function တစ္ခုရဲ႕ local scope ကေန အျပင္က global variable ကို အသံုးျပဳလုိတဲ႔အခါမွာ global keyword သံုးျပီး ဒါဟာ global variable ျဖစ္ပါတယ္ဆိုျပီး defined လုပ္ေပးရပါမယ္။ ဒါဆိုသံုးလို႔ရပါတယ္။ အဲဒီေနာက္ အဲဒီ function ထဲက အဲဒီ variable ကို ေျပာင္းလဲသမွ်ဟာ အျပင္က global scope ထဲက variable ကို သက္ေရာက္မႈရွိမွာျဖစ္ပါတယ္။

example
$var ="hello";
function testFunction()
{
global $var;
$var="world";
}
testFunction();
echo $var;
ဒါေလာက္ဆို global scope နဲ႔ local socpe ကို ကြဲျပားလိမ့္မယ္လို႔ထင္ပါတယ္။ super global variable ေတြအေၾကာင္း ကို ေနာက္ post အေနနဲ႔ ေရးပါဦးမယ္။


Previous
Next Post »

Thorium School

Thorium School
Be professional with us