Skip to content

Instantly share code, notes, and snippets.

@wiyoe
Created May 21, 2018 11:03
Show Gist options
  • Select an option

  • Save wiyoe/54edc22c28cdd790de2086b0cb543709 to your computer and use it in GitHub Desktop.

Select an option

Save wiyoe/54edc22c28cdd790de2086b0cb543709 to your computer and use it in GitHub Desktop.
PHP Closure by Reference
// Set counter
$i = 0;
// Increase counter within the scope
// of the function
$closure = function () use ($i){ $i++; };
// Run the function
$closure();
// The global count hasn’t changed
echo $i; // Returns 0
// Reset count
$i = 0;
// Increase counter within the scope
// of the function but pass it as a reference
$closure = function () use (&$i){ $i++; };
// Run the function
$closure();
// The global count has increased
echo $i; // Returns 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment