declare 結構用來設定一段代碼的執行指令。declare
的語法和其它流程控制結構相似:
directive 部分容許設定 declare
代碼段的行為。目前只認識一個指令:ticks(更多訊息見下面
ticks 指令)。
declare 代碼段中的 statement
部分將被執行--怎樣執行以及執行中有什麼副作用出現取決於
directive 中設定的指令。
declare 結構也可用於全局範圍,影響到其後的所有代碼。
Tick 是一個在 declare 代碼段中直譯器每執行
N 條低級語句就會發生的事件。N
的值是在 declare 中的 directive 部分用
ticks=N 來特殊的。
在每個 tick 中出現的事件是由 register_tick_function()
來特殊的。更多細節見下面的例子。注意每個 tick 中可以出現多個事件。
例子 16-3. 評估一段 PHP 代碼的執行時間
<?php // A function that records the time when it is called function profile($dump = FALSE) { static $profile;
// Return the times stored in profile, then erase it if ($dump) { $temp = $profile; unset($profile); return ($temp); }
$profile[] = microtime(); }
// Set up a tick handler register_tick_function("profile");
// Initialize the function before the declare block profile();
// Run a block of code, throw a tick every 2nd statement declare(ticks=2) { for ($x = 1; $x < 50; ++$x) { echo similar_text(md5($x), md5($x*$x)), "<br />;"; } }
// Display the data stored in the profiler print_r(profile (TRUE)); ?>
|
|
這個例子評估「declare」中的 PHP
代碼,每執行兩條低級語句就記錄一次時間。此訊息可以用來找到一段特定代碼中速度慢的部分。這個過程也可以用其它方法完成,但用
tick 更方便也更容易實現。
Ticks 很適合用來做除錯,以及實現簡單的多任務,後台 I/O 和很多其它任務。
參見 register_tick_function() 和
unregister_tick_function()。