Created
October 20, 2016 23:20
-
-
Save thiagoh/385df55959b000c200f8a79b8bb6df13 to your computer and use it in GitHub Desktop.
PHP 7 Closures example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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