开发者

PHP: $i = $i++ crashed the server

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 br开发者_如何学Pythonowser, 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'


$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.


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.


$ php -r '$i=0; $i = $i++; echo "=> ".$i."\n";'
=> 0
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜