Why the refcount is 2 not 1?

后端 未结 5 1452
心在旅途
心在旅途 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:12

    A refcount of 2, here, is extremely non-obvious. Especially considering the above examples. So what's happening?

    When a variable has a single reference (as did $var1 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. Internally, PHP treats $var1 like a reference (in that the refcount is increased for the scope of this function), with the caveat that if the passed reference happens to be written to, a copy is made, but only at the moment of writing. This is known as "copy on write."

    So, if debug_zval_dump() happened to write to its sole parameter (and it doesn't), then a copy would be made. Until then, the parameter remains a reference, causing the refcount to be incremented to 2 for the scope of the function call.

    -- Credits go to the php manual. Read the whole description that comes with the function and you should've even has asked it.

    --- Edit: Woops, I should read more comments before answering :D Anyways, this is the answer to the question as mentioned before.

提交回复
热议问题