在 php 函數(shù)中,全局變量是指函數(shù)外部定義,可以在函數(shù)內(nèi)部使用的變量。有兩種類型:靜態(tài)全局變量:使用 static 關(guān)鍵字聲明,函數(shù)執(zhí)行后保留。動(dòng)態(tài)全局變量:使用 global 關(guān)鍵字聲明,函數(shù)執(zhí)行后釋放。
PHP 函數(shù)中的全局變量
在 PHP 函數(shù)中,全局變量是指在函數(shù)外定義的變量,可以在函數(shù)內(nèi)部使用。PHP 中有兩種類型的全局變量:
靜態(tài)全局變量:使用 static 關(guān)鍵字聲明,函數(shù)執(zhí)行后仍然保留。
動(dòng)態(tài)全局變量:使用 global 關(guān)鍵字聲明,函數(shù)執(zhí)行后釋放。
靜態(tài)全局變量
function example() { static $counter = 0; $counter++; echo $counter; } example(); // 輸出 1 example(); // 輸出 2 example(); // 輸出 3
登錄后復(fù)制
動(dòng)態(tài)全局變量
$count = 10; function example() { global $count; $count++; } example(); echo $count; // 輸出 11
登錄后復(fù)制
實(shí)戰(zhàn)案例
使用靜態(tài)全局變量跟蹤計(jì)數(shù)器
假設(shè)你有一個(gè)函數(shù)需要跟蹤函數(shù)執(zhí)行的次數(shù),你可以使用靜態(tài)全局變量來實(shí)現(xiàn):
function track_executions() { static $count = 0; $count++; return $count; } // 輸出 1 echo track_executions(); // 輸出 2 echo track_executions(); // 輸出 3 echo track_executions();
登錄后復(fù)制
使用動(dòng)態(tài)全局變量共享數(shù)據(jù)
假設(shè)你有兩個(gè)函數(shù),它們需要訪問相同的變量。你可以使用動(dòng)態(tài)全局變量來實(shí)現(xiàn):
$total = 0; function add_number($num) { global $total; $total += $num; } function get_total() { global $total; return $total; } add_number(10); // 輸出 10 echo get_total(); add_number(20); // 輸出 30 echo get_total();
登錄后復(fù)制