How PHP handles $variable data?

If you're using PHP you're usually don't care how PHP stores variables internally. But if you start working with references you probably better know what's going on behind the scenes.

php-variables.png

(Without) References

Let's assume the following code:

$a="Zaphod";
$b=$a;
$c=$a;

You probably would assume that PHP now keeps the string Zaphod three times in memory. Actually all $a, $b and $c internally(!) reference to the same string Zaphod in memory. See diagram #1.

You, the user, will never know you are actually working with references, because PHP hides this very well. For example: If you change the value of any of this variable the reference just points to the new string:

$c="Beeblebrox";

Now $c internally references to the new value Beeblebrox. See diagram #2.

And after deleting the variable $b:

unset($b);

the variable $a still references to Zaphod. See diagram #3.

With References

If you start using references it's - of course - slightly different. Let's start over:

$a="Zaphod";
$b=&$a;
$c=&$a;

Now $b and $c are real references to the value of $a. If you output the values you'll see no difference. See diagram #4.

But if you change the value of $b...

$b="Beeblebrox";

...you'll also change the value of $a and $c because both are pointing the the same value (btw, a value is stored in a so called zval structure). See diagram #5.

Deleting a variable is likely the same as without references:

unset($b);

And the variable $b disappears but the value (as long as referenced by any other variable) stays in memory. Diagram #6.

Conclusion

Even if you don't know, you're probably using references all the time. You don't need to use references to save memory, because PHP already uses references internally, and hides this very well.

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
About

Kai 'Oswald' Seidler writes about his life as co-founder of Apache Friends, creator of XAMPP, and technology evangelist for web tier products at Sun Microsystems.

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today