php中declare的作用詳解

github_zwl發表於2017-10-09

一般用法是 declare(ticks=N);
拿declare(ticks=1)來說,這句主要作用有兩種:
1、Zend引擎每執行1條低階語句就去執行一次 register_tick_function() 註冊的函式
可以粗略的理解為每執行一句php程式碼(例如:$num=1;)就去執行下已經註冊的tick函式。
一個用途就是控制某段程式碼執行時間,例如下面的程式碼雖然最後有個死迴圈,但是執行時間不會超過5秒。
執行 php timeout.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?php
declare(ticks=1);
// 開始時間
$time_start = time();
// 檢查是否已經超時
function check_timeout(){
    // 開始時間
    global $time_start;
    // 5秒超時
    $timeout = 5;
    if(time()-$time_start $timeout){
        exit("超時{$timeout}秒\n");
    }
}
// Zend引擎每執行一次低階語句就執行一下check_timeout
register_tick_function('check_timeout');
// 模擬一段耗時的業務邏輯
while(1){
   $num = 1;
}
// 模擬一段耗時的業務邏輯,雖然是死迴圈,但是執行時間不會超過$timeout=5秒
while(1){
   $num = 1;
}

2、declare(ticks=1);每執行一次低階語句會檢查一次該程式是否有未處理過的訊號,測試程式碼如下:
執行 php signal.php 
然後CTL+c 或者 kill -SIGINT PID 會導致執行程式碼跳出死迴圈去執行pcntl_signal註冊的函式,效果就是指令碼exit列印“Get signal SIGINT and exi”退出

1
2
3
4
5
6
7
8
9
<?php
declare(ticks=1);
pcntl_signal(SIGINT, function(){
   exit("Get signal SIGINT and exit\n");
});
echo "Ctl + c or run cmd : kill -SIGINT " . posix_getpid(). "\n" ;
while(1){
  $num = 1;
}

相關文章