fork download
  1. <?php
  2.  
  3. function copy_increment($int) {
  4. $int++;
  5. }
  6.  
  7. function reference_increment(&$int) {
  8. $int++;
  9. }
  10.  
  11. function object_increment($object) {
  12. $object->int++;
  13. }
  14.  
  15. function maybe_destroy($object) {
  16. unset($object);
  17. }
  18.  
  19. $object = new StdClass();
  20. $object->int = 1;
  21. $int_val = 1;
  22.  
  23. var_dump($int_val); // 1
  24.  
  25. copy_increment($int_val); // Not passed by reference
  26.  
  27. var_dump($int_val); // 1
  28.  
  29. reference_increment($int_val); // Passed by reference
  30.  
  31. var_dump($int_val); // 2
  32.  
  33. var_dump($object); // int = 1
  34.  
  35. object_increment($object); // Always passed by reference
  36.  
  37. var_dump($object); // int = 2
  38.  
  39. // But here you can see that the parameters are
  40. // still copies, but copies of the pointer and
  41. // un-setting only effects the current scope.
  42. maybe_destroy($object);
  43.  
  44. var_dump($object); // int = 2
Success #stdin #stdout 0.02s 24400KB
stdin
Standard input is empty
stdout
int(1)
int(1)
int(2)
object(stdClass)#1 (1) {
  ["int"]=>
  int(1)
}
object(stdClass)#1 (1) {
  ["int"]=>
  int(2)
}
object(stdClass)#1 (1) {
  ["int"]=>
  int(2)
}