PHP鎺у埗缁撴瀯涔媎eclare

鍐呭鎽樿
declare 缁撴瀯鐢ㄦ潵璁惧畾涓娈典唬鐮佺殑鎵ц鎸囦护銆俤eclare 鐨勮娉曞拰鍏跺畠娴佺▼鎺у埗缁撴瀯鐩镐技
鏂囩珷姝f枃
declare
declare 缁撴瀯鐢ㄦ潵璁惧畾涓娈典唬鐮佺殑鎵ц鎸囦护銆俤eclare 鐨勮娉曞拰鍏跺畠娴佺▼鎺у埗缁撴瀯鐩镐技锛

declare (directive)
    statement
directive 閮ㄥ垎鍏佽璁惧畾 declare 浠g爜娈电殑琛屼负銆傜洰鍓嶅彧璁よ瘑涓や釜鎸囦护锛歵icks锛堟洿澶氫俊鎭涓嬮潰 ticks 鎸囦护锛変互鍙 encoding(鏇村淇℃伅瑙佷笅闈 encoding鎸囦护)銆

Note: encoding 鏄 PHP 5.3.0 鏂板鎸囦护銆

declare 浠g爜娈典腑鐨 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 浠g爜娈典腑瑙i噴鍣ㄦ瘡鎵ц N 鏉′綆绾ц鍙ュ氨浼氬彂鐢熺殑浜嬩欢銆侼 鐨勫兼槸鍦 declare 涓殑 directive 閮ㄥ垎鐢 ticks=N 鏉ユ寚瀹氱殑銆

鍦ㄦ瘡涓 tick 涓嚭鐜扮殑浜嬩欢鏄敱 register_tick_function() 鏉ユ寚瀹氱殑銆傛洿澶氱粏鑺傝涓嬮潰鐨勪緥瀛愩傛敞鎰忔瘡涓 tick 涓彲浠ュ嚭鐜板涓簨浠躲


Example #1 璇勪及涓娈 PHP 浠g爜鐨勬墽琛屾椂闂

<?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));
?> 杩欎釜渚嬪瓙璇勪及鈥渄eclare鈥濅腑鐨 PHP 浠g爜锛屾瘡鎵ц涓ゆ潯浣庣骇璇彞灏辫褰曚竴娆℃椂闂淬傛淇℃伅鍙互鐢ㄦ潵鎵惧埌涓娈电壒瀹氫唬鐮佷腑閫熷害鎱㈢殑閮ㄥ垎銆傝繖涓繃绋嬩篃鍙互鐢ㄥ叾瀹冩柟娉曞畬鎴愶紝浣嗙敤 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鎺у埗缁撴瀯涔媎eclare鐨勮缁嗗唴瀹癸紝鏇村淇℃伅璇峰叧娉∣D浜戝叾瀹冪浉鍏虫枃绔狅紒



鏈枃URL锛http://www.odweb.cn/news_show.html?id=84