1. Local scope
function update_counter()
{
$counter++;//此處$counter為局部變量,與函數外的$counter非同一個
}
$counter = 10;
update_counter();
echo $counter;
//輸出:10
2. Global scope
function update_counter()
{
global $counter;//利用global關鍵字在函數內進行聲明即可獲取全局域的$counter
$counter++;
}
$counter = 10;
update_counter();
echo $counter;
//輸出: 11
function update_counter()
{
$GLOBALS[counter]++;
}
$counter = 10;
update_counter();
echo $counter;
//輸出:11
3. Static variables
function update_counter()
{
static $counter = 0;//利用static關鍵字進行聲明$counter,具有局部域
$counter++;
echo "Static counter is now $counter\n";
}
$counter = 10;
update_counter();
update_counter();
echo "Global counter is $counter\n";
/*輸出:
Static counter is now 1
Static counter is now 2
Global counter is 10
*/