1. 程式人生 > >php中declare示例

php中declare示例

程式碼如下:

echo "<pre>";
//可以用於程式程式碼測試,下面的程式實現了超時退出的功能
$start_time = time();
$singal = false;              //使用全域性變數跳出死迴圈
function check_timeout(){
    global $start_time;
    global $singal;
    $timeout = 5;
    if(time()-$start_time>$timeout){
        $singal = true;
    }
}
register_tick_function(
'check_timeout'); declare(ticks = 5){ $num = 0; while (1) { $a = 0; $num = ++$num; if($singal == true){ //break; goto signal; //使用goto跳轉到指定的位置,也可以使用break中斷迴圈跳出 } } } signal:; //測試declare執行的程式碼塊,作用範圍 $tmp = 0; function timer() {
global $tmp; echo $tmp.'<br>'; } //註冊tick方法 register_tick_function("timer"); //設定每執行幾條語句執行已註冊的方法這裡設定了3/每次 declare(ticks=2){ echo "<pre>"; $tmp += 1; $tmp += 1; $tmp += 1; $tmp += 1; $tmp += 1; $tmp += 1; $tmp += 1; $tmp += 1; $tmp += 1; $tmp +=
1; } //測試ticks是否能使用常量,經過測試ticks的值必須是一個數字 echo "<pre>"; define('LINES',2); $i = 0; function test(){ global $i; echo "<br>exec lines:".(LINES * $i); $i++; } register_tick_function('test'); declare(ticks=2){ function getInfo(){ $sum = 0; for($j = 0; $j<100;$j++){ $sum = $sum + $j; } return $sum; } echo "<br>".getInfo(); }

執行結果:

0
2
4
6
8
10
10

exec lines:010

exec lines:210

exec lines:410

exec lines:610

exec lines:810

exec lines:1010

exec lines:1210

exec lines:1410

exec lines:1610

exec lines:1810

exec lines:2010

exec lines:2210

exec lines:2410

exec lines:2610

exec lines:2810

exec lines:3010

exec lines:3210

exec lines:3410

exec lines:3610

exec lines:3810

exec lines:4010

exec lines:4210

exec lines:4410

exec lines:4610

exec lines:4810

exec lines:5010

exec lines:5210

exec lines:5410

exec lines:5610

exec lines:5810

exec lines:6010

exec lines:6210

exec lines:6410

exec lines:6610

exec lines:6810

exec lines:7010

exec lines:7210

exec lines:7410

exec lines:7610

exec lines:7810

exec lines:8010

exec lines:8210

exec lines:8410

exec lines:8610

exec lines:8810

exec lines:9010

exec lines:9210

exec lines:9410

exec lines:9610

exec lines:9810

exec lines:100
495010

exec lines:102
綜上:decalare(ticks=num)這裡num是執行多少行程式碼,num必須是整形數字。在執行到num的倍數行時回去呼叫
register_tick_function註冊的函式邏輯