在看別人項目過程當中,看到函數裏面不少static修飾的變量,關於static修飾的變量,做用域,用法越看越困惑,因此查了下資料。php
static用法以下:web
1.static 放在函數內部修飾變量函數
2.static放在類裏修飾屬性,或方法oop
3.static放在類的方法裏修飾變量spa
4.static修飾在全局做用域的變量.net
所表示的不一樣含義以下:htm
1.在函數執行完後,變量值仍然保存blog
以下所示:作用域
<?php function testStatic() { static $val = 1; echo $val; $val++; } testStatic(); //output 1 testStatic(); //output 2 testStatic(); //output 3 ?>
2.修飾屬性或方法,能夠經過類名訪問,若是是修飾的是類的屬性,保留值get
以下所示:
<?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 ?>
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' ?>
4.修飾全局做用域的變量,沒有實際意義(存在着做用域的問題,詳情查看)
以下所示:
<?php static $name = 1; $name++; echo $name; ?>
另外:考慮到PHP變量做用域
<?php include '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裏面只有全局做用域和函數做用域,沒有塊做用域
以下所示:
<?php include 'ChromePhp.php'; $age = 0; $age++; for ($i=0; $i<10; $i++) { $age++; } ChromePhp::log($i); //output 10; ChromePhp::log($age); //output 11; ?>
參考資料: