Why the refcount is 2 not 1?

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

    void debug_zval_dump ( mixed $variable );


    Code:

    $var = 1;              # $var's Refcount = 1
    debug_zval_dump($var); # $var is passed by refrence intarlly.
    

    Output:

    long(1) refcount(2)
    

    Explanation: As $var's refcount is 1, PHP optimizes this and handles the memory directly instead of making a copy because there is no chance of contaminating any other references. PHP internally passing $var by reference, so that it can edit the memory directly if it needs too. The second reference is created when actually calling debug_zval_dump().

    A refcount of 2, here, is extremely non-obvious. So what's happening?

    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. Internally, PHP treats $var 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.


    Code:

    $var = 1;              # $var's Refcount = 1
    $var_dup = &$var;      # $var's Refcount = 2
    debug_zval_dump($var); # A copy is passed as $var's refcount is 2.
    

    Output:

    long(1) refcount(1)
    

    Explanation: This time a copy of $var is being made when the function is called. This is because $var is referenced twice and PHP does not want to contaminate any other references so it makes a copy of $var for it's self to work on. As there is now a separate piece of memory that is only used for the scope of the function call it only has one refrence, it's self. So for the scope of the function the copy's refcount is 1 (it's self).

提交回复
热议问题