declareとは
declareとは、実行エンジンに対して、スクリプトの処理方法を指示するための仕組みです。
例
$priceに文字列を代入します。型宣言で引数・戻り値にintを指定しています。
$price = '100'; //文字列を代入
print calc_tax($price);
function calc_tax(int $price): int {
return $price * 0.08;
}
結果は8が返ってきます。文字列が代入されているので、厳密にチェックしたい場合にdeclareを指定します。
declare(strict_types=1);
$price = '100'; //文字列を代入
print calc_tax($price);
function calc_tax(int $price): int {
return $price * 0.08;
}
Fatal error: Uncaught TypeError: Argument 1 passed to calc_tax() must be of the type integer, string given
型が自動で変換されず、エラーが返されます。