Even though it is best to avoid passing a variable by reference to a function in order to avoid altering your application's state outside of the function, PHP 7 makes it possible to pass variables by reference to functions in a highly optimized way even if the reference is a mismatch. Let's take the following code example in order to better understand how PHP 7 is much more efficient in doing so than PHP 5:
// chap3_references.php $start = microtime(true); function test (&$byRefVar) { $test = $byRefVar; } $variable = array_fill(0, 10000, 'banana'); for ($x = 0; $x < 10000; $x++) { test($variable); } $time = microtime(true) - $start; echo 'Time elapsed: ' . $time . PHP_EOL; echo memory_get_usage() . ' bytes' . PHP_EOL;
Let's run this code with the PHP 5 binary:
Here is the result when executing the same code with PHP 7:
The results are once more very impressive as PHP 7 does the same work with almost a third less memory allocation and 1,000 times faster! What is happening under the hood is that PHP 7 no longer makes copies in memory of variables when a reference mismatch occurs. Thus, the new compiler avoids bloating memory allocation for nothing and speeds up the execution of any PHP script where reference mismatches are an issue.