PHP: Simple Reference Example


/ Published in: PHP
Save to your folder(s)

References are like aliases. Instead of assigning memory to the new variable, you're simply pointing to the previous variable.


Copy this code and paste it in your HTML
  1. /************************
  2. Example 1
  3. ************************/
  4. $a = 1;
  5. $b = $a;
  6. $b = 2;
  7.  
  8. echo "a:{$a} / b: {$b}" . "<br />";
  9.  
  10. //$b is now going to become a reference to $a or in other words, an alias
  11. $a = 1;
  12. $b =& $a;
  13. $b = 2;
  14.  
  15. echo "a:{$a} / b: {$b}" . "<br />";
  16.  
  17. //Unset the $b reference (or alias)
  18. unset($b);
  19.  
  20. //$b will not be set to nothing
  21. echo "a:{$a} / b: {$b}";
  22.  
  23. echo "<hr />";
  24.  
  25. /************************
  26. Example 2: Using References as Function Arguments
  27. ************************/
  28.  
  29. //Version 1
  30. function example1(){
  31. global $a;
  32. $a = $a + 1;
  33. }
  34. $a = 10;
  35. example1( $a );
  36. echo $a . "<br />";
  37.  
  38. //Version 2
  39. function example2( &$var ){
  40. //When something comes in, don't take its value, make a reference of it's value
  41. $var = $var + 1;
  42. }
  43.  
  44. $a = 10;
  45. example2( $a );
  46. echo $a . "<br />";

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.