PHP  
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
search for in the  
<switchreturn>
Last updated: Mon, 16 Jul 2012

declare

declare 结构用来设定一段代码的执行指令。declare 的语法和其它流程控制结构相似:

declare (directive) statement

directive 部分允许设定 declare 代码段的行为。目前只认识一个指令:ticks(更多信息见下面 ticks 指令)。

declare 代码段中的 statement 部分将被执行 - 怎样执行以及执行中有什么副作用出现取决于 directive 中设定的指令。

declare 结构也可用于全局范围,影响到其后的所有代码。

<?php
// these are the same:

// you can use this:
declare(ticks=1) {
    // entire script here
}

// or you can use this:
declare(ticks=1);
// entire script here
?>

Ticks

Tick 是一个在 declare 代码段中解释器每执行 N 条低级语句就会发生的事件。N 的值是在 declare 中的 directive 部分用 ticks=N 来指定的。

在每个 tick 中出现的事件是由 register_tick_function() 来指定的。更多细节见下面的例子。注意每个 tick 中可以出现多个事件。

例子 16-1. 评估一段 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()




<switchreturn>
 Last updated: Mon, 16 Jul 2012
 
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: http://manual.phpv.net/
Last updated: Thu Jul 7 19:13:47 2005 CST