Tuesday, November 9, 2010

PHP5 References Explained Visually

If you are having trouble wrapping your head around PHP5 References, especially how objects are now handled, have a look at this handy guide.

6 comments:

Philippe Cloutier said...

Thank you Monte. I would appreciate if the meaning of "is_ref" could be clarified.

mohrt said...

PHP keeps an internal indicator on each variable called "is_ref" that determins if it is a reference or not. This is part of how PHP keeps track of reference counts.

Philippe Cloutier said...

Thank you. In that case, why is is_ref 1 at the top of page 2 ( $c = &$a)?
BTW, it took me some time to understand the result of $c = &$a, although I could make some sense of it. I didn't understand why $b would be copied due to that. I like the visual representation, but some text explanations could help when even if what happens is clear, the reasons why it happens are not

There is some related information on http://www.php.net/manual/en/features.gc.refcounting-basics.php but it doesn't really answer my questions on the above.

mohrt said...

is_ref=1 because this value is a real refernce. Meaning if I change the value of $a, then $c will also be affected. If you notice on the first page $a and $b point to the same value, but is_ref=0. Therefore when $b got a new value, $a retained its value by creating an internal copy.

mohrt said...

I have now added comments next to each example, see if that helps!

Philippe Cloutier said...

This learned me a lot.

What I most notice is:

*Objects are really treated differently from other types in PHP 5. This seems natural and desirable to me, but I'm scared I will be confused if I have to go back to other languages.

*There is one case where PHP could manage memory differently. If you have

$a = "Manifesto...";
$b = $a;

PHP is efficient and only stores the string once. However if you have

$a = "Manifesto...";
$b = $a;
$c = &$a;

PHP is probably less efficient and stores the string (or other scalar types) twice, once for the group of aliases c and a and once for b.


Thank you Monte. If you provide this by pure altruism, I encourage you to license it under a free license. This could be re-used in PHP documentation.