Voting

Please answer this simple SPAM challenge: two plus one?
(Example: nine)

The Note You're Voting On

gnuffo1 at gmail dot com
6 years ago
If you want to know the reference count of a particular variable, then here's a function that makes use of debug_zval_dump() to do so:

<?php
function refcount($var)
{
   
ob_start();
   
debug_zval_dump($var);
   
$dump = ob_get_clean();

   
$matches = array();
   
preg_match('/refcount\(([0-9]+)/', $dump, $matches);

   
$count = $matches[1];

   
//3 references are added, including when calling debug_zval_dump()
   
return $count - 3;
}
?>

debug_zval_dump() is a confusing function, as explained in its documentation, as among other things, it adds a reference count when being called as there is a reference within the function. refcount() takes account of these extra references by subtracting them for the return value.

It's also even more confusing when dealing with variables that have been assigned by reference (=&), either on the right or left side of the assignment, so for that reason, the above function doesn't really work for those sorts of variables. I'd use it more on object instances.

However, even taking into account that passing a variable to a function adds one to the reference count; which should mean that calling refcount() adds one, and then calling debug_zval_dump() adds another, refcount() seems to have aquired another reference from somewhere; hence subtracting 3 instead of 2 in the return line. Not quite sure where that comes from.

I've only tested this on 5.3; due to the nature of debug_zval_dump(), the results may be completely different on other versions.

<< Back to user notes page

To Top