在 PHP 中,"static" 關(guān)鍵字可以用于聲明靜態(tài)變量或方法。靜態(tài)變量和方法不需要實(shí)例化對(duì)象就可以被訪問(wèn)。在本文中,我們主要討論如何使用 "static" 關(guān)鍵字來(lái)賦值。
靜態(tài)變量不會(huì)在每次函數(shù)調(diào)用時(shí)重置,而是在整個(gè)腳本執(zhí)行過(guò)程中共享。例如,在下面的代碼中,靜態(tài)變量 $count 會(huì)累加每次函數(shù)調(diào)用時(shí)的值,而不是從頭開(kāi)始計(jì)數(shù):
function count_calls() { static $count = 0; $count++; echo "This function has been called $count times."; } count_calls(); // 輸出 "This function has been called 1 times." count_calls(); // 輸出 "This function has been called 2 times." count_calls(); // 輸出 "This function has been called 3 times."
在上面的例子中,靜態(tài)變量 $count 被初始化為 0,并在函數(shù)調(diào)用時(shí)逐步增加。通過(guò)在函數(shù)中使用 "static" 關(guān)鍵字,該變量在函數(shù)執(zhí)行過(guò)程中一直存在,即使在函數(shù)執(zhí)行結(jié)束后也是如此。
與此類似,我們還可以使用靜態(tài)方法來(lái)指定值而不必實(shí)例化對(duì)象。例如:
class Counter { public static $count = 0; public static function count_calls() { self::$count++; echo "This class has been called " . self::$count . " times."; } } Counter::count_calls(); // 輸出 "This class has been called 1 times." Counter::count_calls(); // 輸出 "This class has been called 2 times." Counter::count_calls(); // 輸出 "This class has been called 3 times."
在上面的例子中,我們聲明了一個(gè)靜態(tài)屬性 $count 并在靜態(tài)方法 count_calls() 中使用。與上面的函數(shù)不同,這里的靜態(tài)變量是在類聲明中而不是函數(shù)體中定義的。在實(shí)際操作中,我們可以像示例中那樣直接調(diào)用類來(lái)使用該方法。
總的來(lái)說(shuō),"static" 關(guān)鍵字可以被用在多種情形下來(lái)實(shí)現(xiàn)不同的邏輯,例如實(shí)例化對(duì)象前進(jìn)行初始化,全局共享變量,增加應(yīng)用程序的可擴(kuò)展性等。它可以讓代碼更加靈活,更加易于管理。