php7 「declare(strict_types=1)」を使って変数の型を厳格にする

php7より「declare(strict_types=1)」を使用することにより、厳格に変数の型を指定することが可能です。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- PHP 7.4.5
※windows10にApacheのインストールはこちら
※windows10にphpのインストールはこちら
サンプルコード
下記は、「declare(strict_types=1);」 を使用して、引数の型が異なる場合にエラーを出力するサンプルコードとなります。
ファイル名は「test.php」となってます。
1 2 3 4 5 6 7 8 9 10 11 |
<?php declare(strict_types=1); ini_set('display_errors', "On"); ini_set('mbstring.internal_encoding' , 'UTF-8'); function test(int $i){ echo $i; } test("1"); ?> |
関数「test」を実行した際に、引数が文字列になっているのでエラーが発生します。
1 |
Fatal error: Uncaught TypeError: Argument 1 passed to test() must be of the type int, string given, called in C:\Apache24\htdocs\test.php on line 9 and defined in C:\Apache24\htdocs\test.php:6 Stack trace: #0 C:\Apache24\htdocs\test.php(9): test() #1 {main} thrown in C:\Apache24\htdocs\test.php on line 6 |

引数を文字列ではなく、数値を引数として利用するとエラーはなくなります。
1 2 3 4 5 6 7 8 9 10 11 |
<?php declare(strict_types=1); ini_set('display_errors', "On"); ini_set('mbstring.internal_encoding' , 'UTF-8'); function test(int $i){ echo $i; } test(1); ?> |

-
前の記事
javascript 文字列に指定した文字が含まれている位置を取得する 2020.08.09
-
次の記事
javascript 文字列の一部を抽出する 2020.08.09
コメントを書く