PHP 中的 while (true){ 是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4276891/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does while (true){ mean in PHP?
提问by stevenmc
I've seen this code, and I've no idea what it means.
我看过这段代码,我不知道它是什么意思。
while(true){
echo "Hello world";
}
I know what a while loop is, but what does while(true) mean? How many times will it executed. Is this not an infinite loop?
我知道 while 循环是什么,但是 while(true) 是什么意思?它会执行多少次。这不是无限循环吗?
采纳答案by Pekka
Yes, this is an infinite loop.
是的,这是一个无限循环。
The explicit version would be
显式版本是
while (true == true)
回答by Elzo Valugi
回答by Gekkie
This is indeed (as stated already) an infinite loop and usually contains code which ends itself by using a 'break' / 'exit' statement.
这确实(如前所述)是一个无限循环,并且通常包含使用“break”/“exit”语句结束自身的代码。
Lots of daemons use this way of having a PHP process continue working until some external situation has changed. (i.e. killing it by removing a .pid file / sending a HUP etc etc)
许多守护进程使用这种方式让 PHP 进程继续工作,直到某些外部情况发生变化。(即通过删除 .pid 文件/发送 HUP 等来杀死它)
回答by Marco Altieri
Please referes to the PHP documentation currently at: http://www.w3schools.com/php/php_looping.asp
请参阅当前位于的 PHP 文档:http: //www.w3schools.com/php/php_looping.asp
The while loop executes a block of code as long as the specified condition is true.
只要指定的条件为真,while 循环就会执行一段代码。
while (expression) {
statement(s)
}
The while statement evaluates expression, which must return a boolean value. If the expression evaluates to true, the while statement executes the statement(s) in the while block. The while statement continues testing the expression and executing its block until the expression evaluates to false.
while 语句计算表达式,它必须返回一个布尔值。如果表达式的计算结果为真,while 语句将执行 while 块中的语句。while 语句继续测试表达式并执行其块,直到表达式的计算结果为 false。
As a consequence, the code:
结果,代码:
while (true) {
statement(s)
}
will execute the statements indefinitely because "true" is a boolean expression that, as you can expect, is always true.
将无限期地执行语句,因为“true”是一个布尔表达式,正如您所料,它始终为真。
As already mentioned by @elzo-valugi, this loop can be interrupted using a break (or exit):
正如@elzo-valugi 已经提到的,这个循环可以使用中断(或退出)来中断:
while (true) {
statement(s)
if (condition) {
break;
}
}
回答by Ignacio Vazquez-Abrams
It is indeed an infinite loop.
这确实是一个无限循环。