Last active
February 7, 2022 09:10
-
-
Save svandragt/54ed37d93ef552dc50ea959590fc7afa to your computer and use it in GitHub Desktop.
Gotcha: Iterated lists of objects pass by reference in PHP!
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 | |
| // won't be incremented | |
| $a = [ | |
| 0, | |
| 0, | |
| ]; | |
| // !! will be incremented !! | |
| $b = [ | |
| (object)['count' => 0], | |
| (object)['count' => 0], | |
| ]; | |
| foreach ($a as $i) { $i++; } | |
| foreach ($b as $o) { $o->count++; } | |
| var_dump($a, $b); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
output: