User Tools

Site Tools


php:phprefexplained

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

php:phprefexplained [2013/03/16 17:40] (current)
Line 1: Line 1:
 +====== PHP REFERENCES EXPLAINED WITH GRAPHICS ======
 +
 +
 +===== What are references? =====
 +
 +PHP references allow you to make two variables to refer to the same content. To make a reference, we'll use ampersand sign (&​).\\ ​
 +References aren't pointers ! (as in C). Instead, they are symbol table aliases.
 +
 +===== STEP 1 =====
 +
 +{{:​php:​phpref_step1.jpg?​nolink&​ | Step 1 }}
 +
 +First operations:
 +
 +(1) create a variable $a with content '​Joe'​ \\ 
 +(2) make a reference to it, so give an other name ($b) to content '​Joe'​ \\ 
 +
 +<code php>
 +$a = '​Joe';​ //(1)
 +$b = &$a; //(2)
 +</​code>​
 +
 +Both $a and $b shows '​Joe'​.
 +
 +
 +===== STEP 2 =====
 +
 +{{:​php:​phpref_step2.jpg?​nolink&​ | Step 2 }}
 +
 +Operations:
 +(1) create a variable $a with content '​Joe'​ \\ 
 +(2) make a reference $b to $a \\ 
 +(3) assign '​Bob'​ to $b \\ 
 +
 +<code php>
 +echo $a; // it prints “Bob”
 +echo $b; // it prints “Bob”
 +</​code>​
 +
 +
 +===== STEP 3 =====
 +
 +{{:​php:​phpref_step3.jpg?​nolink&​ | Step 3 }}
 +
 +Operations:
 +(1) create a variable $a with content '​Joe'​ \\ 
 +(2) make a reference $b to $a \\ 
 +(3) create a variable $c with content '​Ron'​ \\ 
 +(4) make new reference for $b to $c \\ 
 +
 +
 +<code php>
 +echo $a; // it shows Joe
 +echo $b; // it shows Ron
 +echo $c; // it shows Ron
 +</​code>​
 +
 +**When you unset the reference, you just break the binding between variable name and variable content. This does NOT mean that variable content will be destroyed.**
 +
 +
 +===== STEP 4 =====
 +
 +{{:​php:​phpref_step4.jpg?​nolink&​ | Step 4 }}
 +
 +
 +Operations:
 +(1) create a variable $a with content '​Joe'​ \\ 
 +(2) make a reference $b to $a \\ 
 +(3) unset $b \\ 
 +
 +<code php>
 +echo $a; // it shows Joe
 +echo (isset ($b) ? “set”: “unset”);​ // it shows unset
 +</​code>​
 +
 +
 +===== STEP 5 ===== 
 +
 +Operations:
 +
 +(1) repeat first two steps of STEP 4
 +
 +<code php>
 +$a = '​Joe';​
 +$b = &$a;
 +</​code>​
 +
 +(2) assign null to $a
 +
 +<code php>
 +$a = null;
 +</​code>​
 +
 +(3) assign again a value to $a
 +
 +<code php>
 +$a = '​Another Joe';
 +</​code>​
 +
 +If we'll check after step2,
 +
 +<code php>
 +echo (isset ($a) ? “set”: “unset”);​ // it shows unset
 +echo (isset ($b) ? “set”: “unset”);​ // it shows unset
 +</​code>​
 +
 +and after step3
 +
 +<​code>​
 +echo (isset ($b) ? “set”: “unset”);​ // it shows set
 +</​code>​
 +
 +So, if you want to break the linkage you must use '​unset'​ and not '​null'​.
  
php/phprefexplained.txt · Last modified: 2013/03/16 17:40 (external edit)