Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the refcount is 2 not 1?

  $var = 1;
  debug_zval_dump($var);

Output:

long(1) refcount(2)


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

Output :

long(1) refcount(1)

UPDATE

Very disapointed at the answer...

like image 760
ajx Avatar asked Nov 19 '10 02:11

ajx


2 Answers

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.

like image 87
Mark Tomlin Avatar answered Oct 23 '22 22:10

Mark Tomlin


I think the documentation for this method explains this under the section "Beware the Ref Count":

debug_zval_dump

like image 7
Steve Sheldon Avatar answered Oct 23 '22 23:10

Steve Sheldon