PHP declare 語句


簡介

PHP 中 **declare** 語句的語法類似於其他流程控制結構,例如 while、for、foreach 等。

語法

declare (directive)
{
   statement1;
   statement2;
   . .
}

程式碼塊的行為由指令型別定義。declare 語句中可以提供三種類型的指令——**ticks**、**encoding** 和 **strict_types** 指令。

ticks 指令

tick 是賦予特殊事件的名稱,該事件在執行指令碼中的特定數量語句時發生。這些語句是 PHP 的內部語句,大致等於指令碼中的語句(不包括條件和引數表示式)。任何函式都可以透過 **register_tick_function** 與 tick 事件關聯。註冊的函式將在 declare 指令中指定的 tick 數量後執行。

在下面的示例中,myfunction() 在 declare 結構中的迴圈完成 5 次迭代後每次都執行。

示例

線上演示

<?php
function myfunction(){
   echo "Hello World
"; } register_tick_function("myfunction"); declare (ticks=5){    for ($i=1; $i<=10; $i++){       echo $i."
";    } } ?>

輸出

從命令列執行上述指令碼將產生以下結果:

1
2
3
4
5
Hello World
6
7
8
9
10
Hello World

PHP 還具有 **unregister_tick_function()** 來刪除函式與 tick 事件的關聯。

strict_types 指令

PHP 作為一種弱型別語言,試圖將資料型別適當地轉換為執行特定操作。如果一個函式有兩個整型引數並返回它們的和,並且在呼叫它時任一引數都給出為浮點數,則 PHP 解析器將自動將浮點數轉換為整型。如果不需要這種強制轉換,我們可以在 declare 結構中指定 **strict_types=1**。

示例

線上演示

<?php
//strict_types is 0 by default
function myfunction(int $x, int $y){
   return $x+$y;
}
echo "total=" . myfunction(1.99, 2.99);
?>

浮點引數被強制轉換為整型以執行加法,得到以下結果:

輸出

total=3

但是,使用帶有 strict_types=1 的 declare 結構可以防止強制轉換。

示例

線上演示

<?php
declare (strict_types=1);
function myfunction(int $x, int $y){
   return $x+$y;
}
echo "total=" . myfunction(1.99, 2.99);
?>

輸出

這將生成以下錯誤:

Fatal error: Uncaught TypeError: Argument 1 passed to myfunction() must be of the type integer, float given, called in line 7 and defined in C:\xampp\php\testscript.php:3

encoding 指令

declare 結構具有 encoding 指令,可以使用它來指定指令碼的編碼方案。

示例

<?php
declare(encoding='ISO-8859-1');
echo "This Script uses ISO-8859-1 encoding scheme";
?>

更新於:2020年9月18日

549 次瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.