Detecting whether a PHP variable is a reference / referenced
Full working example:
function EqualReferences(&$first, &$second){ if($first !== $second){ return false; } $value_of_first = $first; $first = ($first === true) ? false : true; // modify $first $is_ref = ($first === $second); // after modifying $first, $second will not be equal to $first, unless $second and $first points to the same variable. $first = $value_of_first; // unmodify $first return $is_ref;}$a = array('foo');$b = array('foo');$c = &$a;$d = $a;var_dump(EqualReferences($a, $b)); // falsevar_dump(EqualReferences($b, $c)); // falsevar_dump(EqualReferences($a, $c)); // truevar_dump(EqualReferences($a, $d)); // falsevar_dump($a); // unmodifiedvar_dump($b); // unmodified
You can use debug_zval_dump
:
function countRefs(&$var) { ob_start(); debug_zval_dump(&$var); preg_match('~refcount\((\d+)\)~', ob_get_clean(), $matches); return $matches[1] - 4;}$var = 'A';echo countRefs($var); // 0$ref =& $var;echo countRefs($var); // 1
This though will not work anymore as of PHP 5.4 as they removed call time pass by reference support and may throw an E_STRICT
level error on lower versions.
If you wonder, where the -4
in the above function come from: You tell me... I got it by trying. In my eyes it should be only 3 (the variable, the variable in my function, the variable passed to zend_debug_zval
), but I'm not too good at PHP internals and it seems that it creates yet another reference somewhere on the way ;)