Last active
February 10, 2017 10:23
-
-
Save gilbitron/5020cb89a85f66075d2a4e0128d14631 to your computer and use it in GitHub Desktop.
Modifying Arrays in PHP Closures
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 | |
$array = []; | |
(function() use ($array) { | |
// Add an item to the array | |
$array[] = 'item'; | |
})(); | |
var_dump($array); | |
/* | |
* Output: | |
* | |
* array(0) { | |
* } | |
* | |
*/ |
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 | |
$array = []; | |
(function() use (&$array) { // Notice the pass by reference | |
// Add an item to the array | |
$array[] = 'item'; | |
})(); | |
var_dump($array); | |
/* | |
* Output: | |
* | |
* array(1) { | |
* [0] => string(4) "item" | |
* } | |
* | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment