Skip to content

Instantly share code, notes, and snippets.

@thiagoh
Created October 20, 2016 23:20
Show Gist options
  • Save thiagoh/385df55959b000c200f8a79b8bb6df13 to your computer and use it in GitHub Desktop.
Save thiagoh/385df55959b000c200f8a79b8bb6df13 to your computer and use it in GitHub Desktop.
PHP 7 Closures example
php > $x = 123;
php > $var4 = static function() use(&$x) {return $x;}; // with 'static'
php > echo $var4();
123
php > echo (function() use(&$x) {return $x;})();
123
php > $var4 = (function() use(&$x) {return $x;}); // without 'static'
php > echo $var4();
123
php > $x = 321;
php > echo $var4(); // value changes because $var4 has a reference to $x, not its value
321
php > $var5 = (function() use($x) {return $x;});
php > echo $var5();
321
php > echo $var4();
321
php > $x = 1000;
php > echo $var4();
1000
php > echo $var5(); // value won't change because $var5 has the value of $x, not a reference
321
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment