Re:How PHP's foreach works
by narcissus on Wednesday February 27, 2013 @06:42PM
(#5295878)
Just always be sure to unset $value afterwards :)
[ Parent
| on HN ]
I don't know PHP. What happens if you forget to unset the reference?
Then you get the joy of being able to play with it later.
$array = array(1,2,3,4,5);
foreach ($array as &$value) {
echo $value; // some non-mutating action
}
$value = 'woops';
print_r($array); // ([0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => woops)That's why I tell the developers on my team that if they're thinking of using references in PHP, then they're probably Doing It Wrong.
Unless they are experienced developers doing complex data structures, this is probably a good advice. References need to be approached very carefully to use them right. It doesn't help that in old PHP versions you had to use references when working with objects, and some people assumed some bad habits from those times and these habits propagate through code without people actually understanding what's going on.
Huh, I've never actually had that problem, but that's a really good point.
Re:How PHP's foreach works
by xkcdfanboy on Wednesday February 27, 2013 @08:20PM
(#5296335)
I can't count the times that references have caused wierd errors in my PHP code. Definitely a good recommendation.
I hear ya. In fact, I got burned by that problem enough times to make a test for it in my PHPCS 'coding standard'... which is basically a handful of standards that look for my stupid, repeated, coding errors :)
Re:How PHP's foreach works
by function_seven on Wednesday February 27, 2013 @09:37PM
(#5296609)
My own standard is this:
foreach ($array as & $ref) {
// Do something with $ref
} unset ($ref);
i.e. put the `unset()` call on the same line as the closing brace, forever "welding" it to that block.Why do you even use references in the first place?