「嚴格類型」模式只檢查代碼中特定點的類型;它不會跟蹤變量發生的所有事情。
具體而言,它會檢查:
- 給該函數的參數,如果類型提示被包括在簽名;這裏給出了兩個函數
int
到一個函數,期望兩個int
s,所以沒有錯誤
- 函數的返回值,如果返回類型提示包含在簽名中;在這裏你沒有類型提示,但如果你有暗示
: int
,那麼仍然沒有錯誤,因爲$a + $b + $c
的結果確實是int
。
這裏有一些例子,做給出錯誤:
declare(strict_types=1);
$a = '1';
$b = '2';
function FunctionName(int $a, int $b)
{
return $a + $b;
}
echo FunctionName($a, $b);
// TypeError: Argument 1 passed to FunctionName() must be of the type integer, string given
或爲回報提示:
declare(strict_types=1);
$a = 1;
$b = 2;
function FunctionName(int $a, int $b): int
{
return $a . ' and ' . $b;
}
echo FunctionName($a, $b);
// TypeError: Return value of FunctionName() must be of the type integer, string returned
注意的是,在第二個例子中,這是不是事實,我們計算出$a . ' and ' . $b
即拋出錯誤,這是我們返回這個字符串的事實,但我們的承諾是返回一個整數。下面將不給出錯誤:
declare(strict_types=1);
$a = 1;
$b = 2;
function FunctionName(int $a, int $b): int
{
return strlen($a . ' and ' . $b);
}
echo FunctionName($a, $b);
// Outputs '7'
'聲明(strict_types = 1);'不可能 –
@AlivetoDie你能解釋我爲何不可以? – Saturn
已經在重複鏈接中給出: - https://stackoverflow.com/questions/37111470/enabling-strict-types-globally-in-php-7 –