PHP之static靜態變數詳解(二)

來源:互聯網
上載者:User

標籤:

在看別人項目過程中,看到函數裡面很多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靜態變數詳解(二)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.