標籤:php
1. 什麼是ticks
我們來看一下手冊上面對ticks的解釋:
A tick is an event that occurs for every N low-level statements executed by the parser within the declare block. The value for N is specified using ticks=N within the declare block‘s directive section.
總結一下:
- tick是一個事件
- tick事件在每執行N條low-level statements就會放生一次,N由declare語句指定
- 可以用register_tick_function()來指定時間的handler,unregister_tick_function()與之對應
至於什麼是low-level statements,在此不做展開,總結來說,low-level statements包括以下幾種情況:
(1)簡單語句:空語句(一個;號),return, break, continue, throw, goto, global, static, unset, echo, 內建的HTML文本,分號結束的運算式等均算一個語句。(2)複合陳述式:完整的if、elseif, while, do...while, for, foreach, switch, try...catch等算一個語句(3)語句塊:{}大括弧算一個語句塊(4)declare本身算一個複合陳述式
所有的statement, function_declare_statement, class_declare_statement構成了low-level statement.
2. tick的坑
一定要注意的一點是:declare()不是一個函數!!!準確的說,他是說一個語言結構,因此可能會有一些你意想不到的行為,比如說,當你在一個檔案當中多次用到declare()時,其解析的原則是:誰在我前面並且理我最近我就用誰,完全無視你的代碼邏輯,這裡不做展開。一個建議的用法是
declare(ticks=10){ for($i = 0; $i < 20; $i++){ print "hello\n"; }}declare(ticks=2){ for($i = 0; $i < 20; $i++){ print "hello\n"; }}
3. tick的應用
說了這麼多,我們到底什麼時候會用到tick呢?一般來說,tick可以用作調試,效能測試,實現簡單地多任務或者做背景I/O操作等等。
這邊舉一個鳥哥提供的範例,用於完成通訊
<?php/* * 利用ticks來完成訊息通訊 *///create a message queue$mesg_key = ftok(__FILE__, 'm');$mesg_id = msg_get_queue($mesg_key, 0666);//ticks callbackfunction fetchMessage($mesg_id) { if (!is_resource($mesg_id)) { print_r("Mesg Queue is not Ready \n"); } if (msg_receive($mesg_id, 0, $mesg_type, 1024, $mesg, false, MSG_IPC_NOWAIT)) { print_r("Process got a new incoming MSG: $mesg \n"); }}//register ticks callbackregister_tick_function("fetchMessage", $mesg_id);//send messages;declare(ticks = 2) { $i = 0; while (++$i < 100) { if ($i % 5 == 0) { msg_send($mesg_id, 1, "Hi: Now Index is :" . $i); } }}
我們來看一下輸出:
我們發現,由於註冊了tick事件的callback,每經過兩個statements都會觸發tick事件,從而執行了從訊息佇列當中取訊息的操作。這樣就類比了訊息的發送和接收的過程。