什么是靜態(tài)變量?
靜態(tài)變量 類型說明符是static。
靜態(tài)變量屬于靜態(tài)存儲方式,其存儲空間為內(nèi)存中的靜態(tài)數(shù)據(jù)區(qū)(在靜態(tài)存儲區(qū)內(nèi)分配存儲單元),該區(qū)域中的數(shù)據(jù)在整個程序的運行期間一直占用這些存儲空間(在程序整個運行期間都不釋放),也可以認(rèn)為是其內(nèi)存地址不變,直到整個程序運行結(jié)束。
靜態(tài)變量雖在程序的整個執(zhí)行過程中始終存在,但是在它作用域之外不能使用。
只要在變量前加上關(guān)鍵字static,該變量就成為靜態(tài)變量了。
php靜態(tài)變量的作用
1、在函數(shù)內(nèi)部修飾變量。靜態(tài)變量在函數(shù)被調(diào)用的過程中其值維持不變。
<?php function testStatic() { static $val = 1; echo $val."<br />";; $val++; } testStatic(); //output 1 testStatic(); //output 2 testStatic(); //output 3 ?>
程序運行結(jié)果:
1 2 3
2、在類里修飾屬性,或方法。
修飾屬性或方法,可以通過類名訪問,如果是修飾的是類的屬性,保留值
<?php class Person { static $id = 0; function __construct() { self::$id++; } static function getId() { return self::$id; } } echo Person::$id; //output 0 echo "<br/>"; $p1=new Person(); $p2=new Person(); $p3=new Person(); echo Person::$id; //output 3 ?>
程序運行結(jié)果:
0 3
3、在類的方法里修飾變量。
<?php class Person { static function tellAge() { static $age = 0; $age++; echo "The age is: $age "; } } echo Person::tellAge(); //output 'The age is: 1' echo Person::tellAge(); //output 'The age is: 2' echo Person::tellAge(); //output 'The age is: 3' echo Person::tellAge(); //output 'The age is: 4' ?>
程序運行結(jié)果:
The age is: 1 The age is: 2 The age is: 3 The age is: 4