C lets you define variables with block scope: int main(int argc, char *argv[]) {
for(int i=0;i<10;++i)
printf("%d\n", i);
printf("%d\n", i);
}
The last line fails to compile—'i' is no longer defined after exiting the loop.Java: public static void main(String[] args) {
for(int i=0;i<10;++i)
System.out.println(i);
System.out.println(i);
}
That also won't compile.Coming from a language that supports variables with block scope, PHP's behavior is very surprising indeed. If the first mention of $object is in the loop, I can understand someone expecting $object in the second loop to be a distinct variable that just happens to share the same name. This behavior is even surprising coming from Perl, though for a slightly different reason: @array = ('c', 'c++', 'java', 'perl');
foreach $item (@array) {
if($item eq 'perl') {
$item = 'php';
}
}
foreach $item (@array) {
print $item . "\n";
}
For that matter, PHP's reference semantics are a little surprising in general coming from any other language I've ever used. |