tags:

views:

297

answers:

4

This happened to me a few years ago before I knew about SO, but I'm still curious. When I was still learning the basics of PHP, I accidentally typed $i = $i++; When I tested the webpage in the browser, The server crashed and it took a long time to get it back up. I've typed in some pretty stupid things before and created a bunch of infinite loops, but for some reason, that was the worst. Does anyone know why this line was so 'poisonous'

A: 

There's nothing there that would crash a server. Just tried it!

Erik
A: 
$ php -r '$i=0; $i = $i++; echo "=> ".$i."\n";'
=> 0
CodeBlock
+8  A: 

$i = $i++; is the same as $i = $i; essentially.

Unfortunately $i = $i++; is known as "undefined behavior".

Anything could happen simply because the compiler can't fully comprehend what is going on.

There's an excellent SO question covering similar undefined behavior here.

Daniel May
That sounds right, we were using a really finicky server which would explain why other people can pull it off without crashing.
Brian
My guess is, a few years ago, that PHP Version that the server was running would crash if that code was ran. Not sure.
Jimmie Lin
Yep. The reassignment to `i` (explicitly) is absolutely redundant. Can see how a beginner could stumble across this though. Shame it's so unforgiving.
Daniel May
Nice euphemistic term: "undefined behavior" for crashing one's server.
Toad
It's a leap to use the label "undefined behavior" for this. All PHP expressions have return values; the return value of $i++ is merely being assigned to $i, redundant as that may be. There's nothing for the compiler to not "comprehend", and I'm with those who think op is/was confused.
GZipp
+2  A: 

This should not crash anything.

$i = $i++;
var_dump($i); // NULL;

From the PHP Manual

It is not necessary to initialize variables in PHP however it is a very good practice. Uninitialized variables have a default value of their type depending on the context in which they are used.

Also, by default, variables are always assigned by value and since you are using a Post Increment, the value of the uninitialized $i (NULL) is assigned first by copy to $i, effectively overwriting itself. See this code to see what happens:

$i = 0
$i = $i++;
var_dump($i); // int(0);

I don't know if PHP will still try to increment the right hand variable value after the assignment. If you are interested in that, install the PECL extension Parsekit and check the OP codes for further details.

So it was likely something else that crashed your server.

Gordon