LoginSignup
2
0

More than 3 years have passed since last update.

PHPで厳密な型チェック「declare」

Posted at

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

型が自動で変換されず、エラーが返されます。

参考

独習PHP 第3版

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0