by BadCRC · 14y ago · 0 comments
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. #include <stdio.h>
int main()
{
int arr[10] = {1,2,3,4,5,6,7,8,9,0}, *ptr;
for(int i = 10; i>=0; i--)
{
ptr = &arr[i];
printf("%d\n", *ptr);
}
printf("%d\n", *ptr);
}Also note that, in C, you have to explicitly dereference pointers:
ptr = 42;
You should get a warning from your compiler if you try that. PHP effectively goes ahead and changes it to: *ptr = 42;
Perl requires you to explicitly dereference references as well: @array = ('c', 'c++', 'java', 'perl');
$item = \$array[3];
$item = 'php'; # Does NOT replace the item in the array
foreach $item (@array) {
print $item . "\n";
}
PHP is weird in this regard: if you ever assign a reference to a variable, later assignments go through that reference automatically. To convert the variable back to a normal variable, you have to unset it. I don't know of another language that acts like this. Can you think of one?Combine that with the lack of block scope, and you get surprises like the example BadCRC linked.
(Yes, the "what if you add another statement line later?!" trope has been registered.)