前端PHP入門-016-靜態變數

來源:互聯網
上載者:User

標籤:

如果我想知道函數被調用了多少次怎麼辦?在沒有學習靜態變數的時候,我們沒有好的辦法來解決。

靜態變數的特點是:聲明一個靜態變數,第二次調用函數的時候,靜態變數不會再初始設定變數,會在原值的基礎上讀取執行。

先執行10次demo()函數試試,再執行10次test()函數試試:

  1. <?php
  2. function demo(){
  3. $a = 0;
  4. echo $a;
  5. $a++;
  6. }
  7. ?>
  8. <?php
  9. function test(){
  10. static $a = 0;
  11. echo $a;
  12. $a++;
  13. }
  14. ?>
  15. demo();
  16. demo();
  17. demo();
  18. demo();
  19. demo();
  20. demo();
  21. demo();
  22. demo();
  23. demo();
  24. demo();
  25. /*
  26. for($i = 0 ;$i < 10 ; $i++){
  27. test();
  28. }
  29. */

上例中你會發現:
test();執行一次數值就會加1,而demo輸出的顯示結果,始終為0。

通過上例你就會發現,本文開始處說明的靜態變數的特點。



來自為知筆記(Wiz)

前端PHP入門-016-靜態變數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.