declare(strict types=1)
declare(strict types=1)
によって暗黙castを防ぐ
ただし色々気をつける点がある
厳し目になる
declare(strict_types=1)
phpdeclare(strict_types=1);
暗黙のcastを防ぐ
挙動の変化を見る
i()
も f()
も引数をそのまま返す関数
返り値の型を指定することで暗黙castが行われる
phpfunction i(int $n): int { return $n; }
function f(float $n): float { return $n; }
$num = 1.1;
dump(i($num)); // 1 ←そのまま返しているのにcastされている
dump(f($num)); // 1.1
strict_typesを付けるとエラーが表示される
実行時にもエラーが出される
phpdeclare(strict_types=1); // これを加えた
function i(int $n): int { return $n; }
function f(float $n): float { return $n; }
$num = 1.1;
dump(i($num)); // error: Expected type 'int'. Found 'float'
dump(f($num));
実行時にも Type error: Argument 1 passed to .. must be of the type integer, float given, called in
のようなエラーが表示される
しかし、これは実行されなければ実行時エラーは出ない
phpdeclare(strict_types=1);
if(false){
// さっきのコード
}
気をつける
「既に大量に書かれたPHPコードがあるファイル」に
あとからstrict_typesを付け加えるのは、かなり怖い
「暗黙cast」をしている部分が一箇所もなければ大丈夫
「そのファイル内の全関数が返り値の型を指定していない」でも大丈夫なのか
少なくとも「型エラーを全消しした状態」にしないと付け加えたくない
でも新しく書く場合ならこっちの方がいいのかもな
