Created
May 21, 2018 11:03
-
-
Save wiyoe/54edc22c28cdd790de2086b0cb543709 to your computer and use it in GitHub Desktop.
PHP Closure by Reference
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
| // 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