Skip to content

Instantly share code, notes, and snippets.

@mxr576
Last active September 8, 2017 19:19
Show Gist options
  • Save mxr576/309090e74bfae97f54a62648c604a24c to your computer and use it in GitHub Desktop.
Save mxr576/309090e74bfae97f54a62648c604a24c to your computer and use it in GitHub Desktop.
Why you should not use pass by reference in PHP

First example

Run: https://3v4l.org/VV51q

<?php

$a = 1; $b = &$a; $b = 42; print $a;

This is pretty simple, isn't it?

Output: 42.

Second example

Run: https://3v4l.org/odmZU

<?php

$array = array_reverse(range(1, 42));

foreach ($array as &$value) {
  // do nothing;
}

$array = array_reverse($array);

foreach ($array as $value) {
  // do nothing;
}

print reset($array);

This isn not that obvious, isn't it?

Output: 42.

Third example

Run: https://3v4l.org/GmeeL

What about closures?

<?php

$param = 666;

function meaningOfLife() {
  $param = 1;
  $func = function() use(&$param) {
    $param = 42;
  };
  $func();
  print $param;
}

meaningOfLife();

Output: 42.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment