【php学习笔记】ticks篇
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 callback function 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 callback register_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事件。從而運行了從消息隊列其中取消息的操作。這樣就模擬了消息的發送和接收的過程。
轉載于:https://www.cnblogs.com/jhcelue/p/7019241.html
總結
以上是生活随笔為你收集整理的【php学习笔记】ticks篇的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: 在web.config中配置httpHa
 - 下一篇: 模块和内置函数