Skip to main content

Passing by value vs reference

In some languages, you have to pay attention to using variables from a greater scope (e.g. a global variable or function variable) inside an anonymous function, if you intend to return the same reference back.

PHP Example

Here's some code using promises:

use GuzzleHttp\Promise;
use GuzzleHttp\Client;

$client = new Client([
    // Base URI is used with relative requests
    'base_uri' => 'http://httpbin.org',
    // You can set any number of default request options.
    'timeout'  => 2.0,
]);

$results = [];
// Let's assume the function returns the string "123".
$promise = $client->requestAsync('GET', 'http://httpbin.org/get');
$promise->then(
		function ($value) {
			$results[] = $value;
		}
);
$promise->wait();
// Expected output: the string "123" has been added to our results array.
echo print_r($results, true);
// Actual output: the results array is empty.

By default, PHP passes function arguments by value. The $results array inside the promise's anonymous function is considered a local variable; the anonymous function doesn't know the $results array outside exists.

To fix this, you need to use the PHP deferencing operator,operator &, which has slightly weird syntax:

function ($value) use (&$results) {
  $results[] = $value;
}

This lets the anonymous function have access to the outside $results variable, and add the new value entry to it.