note 99644 added to language.references
| From: | gnuffo1 at gmail dot com | Date: | Sat, 28 Aug 2010 02:07:30 +0000 |
| Subject: | note 99644 added to language.references | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-172126@lists.php.net to get a copy of this message | ||
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.
----
Server IP: 69.147.83.197
Probable Submitter: 78.143.196.200
----
Manual Page -- http://www.php.net/manual/en/language.references.php
Edit -- https://master.php.net/note/edit/99644
Del: integrated -- https://master.php.net/note/delete/99644/integrated
Del: useless -- https://master.php.net/note/delete/99644/useless
Del: bad code -- https://master.php.net/note/delete/99644/bad+code
Del: spam -- https://master.php.net/note/delete/99644/spam
Del: non-english -- https://master.php.net/note/delete/99644/non-english
Del: in docs -- https://master.php.net/note/delete/99644/in+docs
Del: other reasons-- https://master.php.net/note/delete/99644
Reject -- https://master.php.net/note/reject/99644
Search -- https://master.php.net/manage/user-notes.php