"厳密な型"モードは、コード内の特定のポイントでのみ型をチェックします。それは変数に起こるすべてを追跡しません。
具体的には、チェック:機能に与え
- パラメータを、タイプヒントが署名に含まれている場合、ここでは2つの
int
を期待する関数に2つのint
を与えているので、返り値のヒントがシグネチャに含まれていれば、エラーはありません。
- 関数の戻り値。ここにタイプヒントはありませんが、ヒントが
: 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 –