Re: Confusing pointers in PHP 4 and 5
| From: | Sara Golemon | Date: | Wed, 09 Jun 2004 16:56:38 +0000 |
| Subject: | Re: Confusing pointers in PHP 4 and 5 | ||
| References: | 1 2 3 4 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-10349@lists.php.net to get a copy of this message | ||
> I think, and I could be completely wrong, that copying a variable actually
> creates a reference. The data is only copied when the variable referenced
is
> modified.
>
That's true. What I left out of my explanation (in order to keep it simple)
is that when you "copy" a variable, a new label is created to point to the
same zval, and the zval's refcount is incrmented but the is_ref flag is
*not* set (I referred to this offhand as non-reference manner of multiple
labels referring to the same value). Then when one of the referring labels
says "I want to change my
copy of the data." It notices that someone else
is also referring to this value (in a non-reference manner) and "separates"
the zval: This amounts to making a true copy of the zval (with a refcount
of 1, and an is_ref of 0) and decrements the refcount of the original zval
(since one fewer label is referring to it). This is the process known as
"copy on change".
$foo = 1;
/* $foo (label) ------> 1(value) (is_ref:0 refcount:1) */
$bar = $foo;
/* $foo (label) -------> 1(value) */
/* $bar (label) ---/ (is_ref:0 refcount:2) */
$foo = 2;
/* $bar (label) -------> 1(value) (is_ref:0 refcount:1) */
/* $foo (label) -------> 2(value) (is_ref:0 refcount:1) */
-Sara
Ya just had to make it complicated didn't you.