What is the difference between “GLOBAL” and “STATIC” variable in PHP?

前端 未结 4 1760
眼角桃花
眼角桃花 2021-01-02 10:29

What exactly is the difference between the GLOBAL and STATIC variables in PHP? And which one is preferable to use, when we want to use a variable in multiple functions?

4条回答
  •  执笔经年
    2021-01-02 10:58

    Global variable is created before the function is created, but global keyword is added in function

    $g_var = 1;
    
    function test() {
      var_dump($GLOBAL['g_var']);
      global $g_var;
      var_dump($g_var);
    } 
    

    static is created and declared static in function

    function test() {
      static $cnt = 0;
      $cnt ++;
      echo $cnt;
    }
    
    $i = 10;
    
    while(--$i) test();
    

提交回复
热议问题