Why the refcount is 2 not 1?

后端 未结 5 1486
心在旅途
心在旅途 2021-01-02 10:44
  $var = 1;
  debug_zval_dump($var);

Output:

long(1) refcount(2)


  $var = 1;
  $var_dup = &$var;
  debug_zval_dump($var);exit         


        
5条回答
  •  孤独总比滥情好
    2021-01-02 11:14

    Code:

    $var = 1;
    debug_zval_dump($var);
    

    Output: long(1) refcount(2)

    Explanation: When a variable has a single reference, as did $var before it was used as an argument to debug_zval_dump(), PHP's engine optimizes the manner in which it is passed to a function. PHP, basically makes a pointer to the variable and internally, PHP treats $var like a reference and so it's refcount is increased for the scope of this function.

    Code:

    $var = 1;
    $var_dup = &$var;
    debug_zval_dump($var);exit;
    

    Output: long(1) refcount(1)

    Explanation: Here the $var variable is copyied on write, making whole new seprate instance of that varable and because debug_zval_dump is dealing with a whole new copy of $var, not a reference, it's refcount is 1. The copy is then destroyed once the function is done.

    Hope that clears it up.

提交回复
热议问题