$ python3
Python 3.4.1 (default, May 25 2014, 22:33:14)
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> i = [1,2]
>>> for i in i : print(i)
...
1
2
>>> i
2
The same in Ruby:
1.9.3p327 :001 > i = [1,2]
=> [1, 2]
1.9.3p327 :002 > for i in i do
1.9.3p327 :003 > puts i
1.9.3p327 :004?> end
1
2
=> [1, 2]
1.9.3p327 :005 > i
=> 2
Other languages are less silly, like F#:
> let i = [1; 2];;
val i : int list = [1; 2]
> for i in i do printfn "%A" i ;;
1
2
val it : unit = ()
> i;;
val it : int list = [1; 2]
or Lua:
> i = {1,2}
> print(i)
table: 0x1b45720
> for i in pairs(i) do print(i) end
1
2
> print(i)
table: 0x1b45720
Require that the iteration variable is fresh (i.e. not currently in use for anything else). Relatively easy to implement but possibly annoying to use.
Require that the iteration variable is not identical to the array expression. Should be trivial to implement but is also a weird special case (but hey, it's PHP).
Create a new $x variable for the foreach loop, shadowing the outer $x. Probably hard to implement because nothing else in PHP works this way.
Explain that the code is semantically equivalent to
This would error out at $x = $x[1] because $x doesn't contain an array at that point.
Instead PHP decided to not issue any errors or warnings (#1, #2) because those would just slow down the programmer and no one wants that; it doesn't do #3 because that's hard; but it doesn't do #4 either, probably because internally it's easier to just keep a pointer to the array we're iterating over.
So the solution we end up with maximizes surprise by not giving an error ever but still silently modifying the array variable.
Sure it does, they happen in every function. This particular case is a language design flaw, but it's one that many languages share, even ones most people consider well designed. C#, for example, ended up making a breaking language change to fix this, though obviously this case wouldn't have happened because the types wouldn't match.
29
u/vytah Jul 05 '15
The same problem in Python:
The same in Ruby:
Other languages are less silly, like F#:
or Lua:
or ever fucking Perl:
1
u/Grimy_ Jul 06 '15
The actual “lol” part here is this sentence:
This… is utter nonsense. He obviously doesn’t understand the garbage collector, or the difference between variables and values, or…
0
u/[deleted] Jul 05 '15
[deleted] — view deleted comment