PHP 并不神奇,不能像那样停止执行中间脚本。这while
仅当所有处理都在您的内部时才会检查条件include
已完成。
您可以尝试拨打电话register_tick_function() http://php.net/manual/en/function.register-tick-function.php
并提供一个回调来检查经过的时间和exit http://php.net/manual/en/function.exit.php
如果需要的话。
现在有更多的例子!
<?php
declare(ticks=1);
define('START_TIME', time());
// lambda uses START_TIME constant
register_tick_function(function() {
if (time() - START_TIME > 20) {
echo 'Script execution halted. Took more than 20 seconds to execute';
exit(1);
}
}, true);
include_once 'onefile.php';
include 'somefile.php';
include 'somefile2.php';
?>
这将在下一个停止tick http://php.net/manual/en/control-structures.declare.php#control-structures.declare.ticks这发生在 20 秒标记之后,而不是正好 20 秒。
根据您当前的更新编辑 #2 工作代码
该代码的工作原理类似,但它不是停止脚本执行,而是抛出一个TimeLimitException
然后用于跳转到执行点goto http://php.net/manual/en/control-structures.goto.php。它很hacky,但它可以完成你所需要的。
<?php
declare(ticks=1);
$start_time = time();
class TimeLimitException extends Exception {}
// lambda uses $start_time global so it can reset
// the timer after the time limit is reached
register_tick_function(function() {
global $start_time;
if (time() - $start_time > 20) {
echo 'Script execution halted. Took more than 20 seconds to execute', PHP_EOL;
$start_time = time();
throw new TimeLimitException();
}
}, true);
try {
// time limit will reset to here. Cannot jump to a label in a loop
limit:
while (1) {
sleep(1);
echo 'outer ';
while (1) {
echo 'inner ';
sleep(2);
}
}
} catch (TimeLimitException $e) {
echo 'time limit hit, jumping to label `limit`', PHP_EOL;
goto limit;
}