Why the refcount is 2 not 1?

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

    I'll try to give some more light to the debug_zval_dump() function and the way you process your variables. Don't kill me if I'm wrong :)...

      $var = 1;
      debug_zval_dump($var);
    

    I think the debug function counts the $var refcount(1) and the 1 refcount(2) since 1 is the value of $var.
    If you look at it logically you are actually saying this.

      1 = 1;
      debug_zval_dump(1);
    

    Second part:

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

    What you see here is that you set $var to $var_dup but is keeping its value. The refcount of $var is 1 because you 'linked' it to $var_dup.

    $var = 2;
    $var_dup = &$var; //or $var = &$var_dup; (doesn't matter which one)
    $var = 3;
    debug_zval_dump($var_dup);exit;
    

    This gives long(3) refcount(1)... Why is it refcount 1? As you can see the value of $var_dup was never assigned to 3, it should be 2 right? No it shouldn't because you keep it up to date with &$var. This means that when you past $var = 4 between $var = 3 and debug_zval_dump($var_dup);exit; the value of $var_dup will be updated automatically because you have linked them, making it 1 refcount.

    Then there is this other occurrence:

    $var = 2;
    $var_dup = $var;
    $var = 4;
    debug_zval_dump($var_dup);exit;
    

    The output of this is: long(2) refcount(2). As you can see the value of $var_dup is correct. $var was 2, the value was passed through $var_dup an he sticked with it. The refcount is 2 because is counts $var = 4; and $var_dup = $var;. When we remove the $var = 4; we get this:

    $var = 2;
    $var_dup = $var;
    debug_zval_dump($var_dup);exit;
    

    The output of this is: long(2) refcount(3). Now the debug function count the following: $var_dup(1), =$var(2) (since $var_dup was originated from $var) and $var(= 2;)(3).

    I'll hope you understand what I mean. In my opinion this is more math then programming, so that may be the reason why it is a difficult function to understand.

    And again, if I'm wrong, don't kill me :)...
    Greetings,
    Mixxiphoid

    Disclaimer
    I do not know what the purpose is of this function. I actually never heard of it until today. So I'm not responsible for inappropriate use :).

提交回复
热议问题