dousi1970 2012-05-31 01:20
浏览 58
已采纳

有人可以为我清理静态变量吗?

Using PHP here, I decided to read through the manual chapter by chapter and learn new things. So now I've discovered static variables, which seem like an awesome concept, but the way I understand it is:

Static variables are set once and only once per load of the script. They can be changed and incremented but not actually re-set. Usually used in functions to set a value and not have to initialize that variable every time the function runs.

<?php

function count2( $inputNum ) {
    static $a = $inputNum;
    echo $a++; //Echo and then increment.
}

for ( $i = 0; $i < 10; $i++ ) {
    count2(50);
}

?>

I'd expect this to start the static $a var at 50, and increment 11 times. How come I get an error?

  • 写回答

3条回答 默认 最新

  • dongluo3962 2012-05-31 01:24
    关注

    The static variable cannot be initialized with another variable, whose value is not known until runtime. You must initialize it with a value known at compile time.

    function count2($inputNum) {
      // Initialize only once to an integer (non variable, non-expression)
      static $a = 0;
      if ($a === 0) {
        // If $a is still 0, set it to $inputNum
        $a = $inputNum;
      }
      echo $a++;
    }
    
    // First run outputs 25
    count2(25);
    // 25
    // Subsequent runs increment
    count2(25);
    // 26
    count2(25);
    // 27
    

    Relevant documentation...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元