標籤:
在看別人項目過程中,看到函數裡面很多static修飾的變數,關於static修飾的變數,範圍,用法越看越困惑,所以查了下資料。
static用法如下:
1.static 放在函數內部修飾變數
2.static放在類裡修飾屬性,或方法
3.static放在類的方法裡修飾變數
4.static修飾在全域範圍的變數
所表示的不同含義如下:
1.在函數執行完後,變數值仍然儲存
如下所示:
<?phpfunction testStatic() {static $val = 1;echo $val;$val++;}testStatic();//output 1testStatic();//output 2testStatic();//output 3?>
2.修飾屬性或方法,可以通過類名訪問,如果是修飾的是類的屬性,保留值
如下所示:
<?phpclass Person {static $id = 0;function __construct() {self::$id++;}static function getId() {return self::$id;}}echo Person::$id;//output 0echo "<br/>";$p1=new Person();$p2=new Person();$p3=new Person();echo Person::$id;//output 3?>
3.修飾類的方法裡面的變數
如下所示:
<?phpclass 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‘?>
4.修飾全域範圍的變數,沒有實際意義(存在著範圍的問題,詳情查看)
如下所示:
<?phpstatic $name = 1;$name++;echo $name;?>
另外:考慮到PHP變數範圍
<?phpinclude ‘ChromePhp.php‘;$age=0;$age++;function test1() {static $age = 100;$age++;ChromePhp::log($age); //output 101}function test2() {static $age = 1000;$age++;ChromePhp::log($age); //output 1001}test1();test2();ChromePhp::log($age); //outpuut 1?>
可以看出:這3個變數是不相互影響的,另外,PHP裡面只有全域範圍和函數範圍,沒有塊範圍
如下所示:
<?phpinclude ‘ChromePhp.php‘;$age = 0;$age++;for ($i=0; $i<10; $i++) {$age++;}ChromePhp::log($i); //output 10;ChromePhp::log($age); //output 11;?>
參考資料:
- PHP: static variable in function, class, method
- Static Keyword
- Variable scope
- Variables
PHP之static靜態變數詳解(二)