2017-08-02 41 views
0
<?php 
declare(strict_types=1); 
$a = 1; 
$b = 2; 
function FunctionName(int $a, int $b) 
{ 
    $c = '10'; //string 
    return $a + $b + $c; 
} 
echo FunctionName($a, $b); 
?> 

我預計FunctionName($a, $b)會打印一個錯誤,但它不會打印錯誤消息。如您所見,我向int($a+$b)添加了一個字符串($c),並聲明strict_types=1'strict_types = 1'似乎在某個功能中不起作用

爲什麼我不能收到錯誤信息?

+0

'聲明(strict_types = 1);'不可能 –

+0

@AlivetoDie你能解釋我爲何不可以? – Saturn

+0

已經在重複鏈接中給出: - https://stackoverflow.com/questions/37111470/enabling-strict-types-globally-in-php-7 –

回答

1

「嚴格類型」模式只檢查代碼中特定點的類型;它不會跟蹤變量發生的所有事情。

具體而言,它會檢查:

  • 給該函數的參數,如果類型提示被包括在簽名;這裏給出了兩個函數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' 
+0

非常感謝。現在我更清楚地理解它了。 – Saturn