declare

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

declare (directive)
    statement

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

Note: encoding 是 PHP 5.3.0 新增指令。

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

declare 结构也可用于全局范围,影响到其后的所有代码(但如果有 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

Caution

ticks 指令在 PHP 5.3.0 中是过时指令,将会从 PHP 6.0.0 移除。

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

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

Example #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()

Encoding

A script's encoding can be specified per-script using the encoding directive.

Example #2 Declaring an encoding for the script.

<?php
declare(encoding='ISO-8859-1');
// code here
?>

Caution

When combined with namespaces, the only legal syntax for declare is declare(encoding='...'); where ... is the encoding value. declare(encoding='...') {} will result in a parse error when combined with namespaces.

The encoding declare value is ignored in PHP 5.3 unless php is compiled with --enable-zend-multibyte. In PHP 6.0, the encoding directive will be used to inform the scanner what encoding the file is created in. Legal values are encoding names such as UTF-8.


PHP MySQL HTML CSS JavaScript MSSQL AJAX .NET JSP Linux Mac ASP 服务器 SQL jQuery C# C++ java Android IOS oracle MongoDB SQLite wamp 交通频道