中級 › declare(strict_types=1) で型の異なる引数を渡すと TypeError になる › パターン3
declare(strict_types=1) で型の異なる引数を渡すと TypeError になる
ファイルの先頭でdeclare(strict_types=1)を宣言すると、関数の型宣言と異なる型の値を渡した際に自動変換されず、TypeErrorになります。
1 <?php 2 declare(strict_types=1); 3 function repeat(string $s, int $times): string { 4 return str_repeat($s, $times); 5 } 6 echo repeat("ab", _______); ^
Fatal error: Uncaught TypeError: repeat(): Argument #2 ($times) must be of type int, string given, called in main.php on line 6 and defined in main.php:3
空欄を埋めて実行を通す
int型の引数に文字列"3"を渡すと、strict_types下では自動変換されずTypeErrorになります。
次の問題