そーくのつれづれぶろぐ

web系エンジニアの勉強したことなど

【PHP7】declare(strict_types=1)の挙動

自分の言葉でメモをする。

declare(strict_types=1)の効力範囲

一言でいうと「declare(strict_types=1)を記載しているファイル内で関数を呼び出すときに厳密に型が検査される」

qiita.com

つける/つけないのふるまいの違い

引数にstringを持つshow()関数(後述参照)で試した結果が以下。

  • 文字通り型がちがうかどうかの厳密さ
  • 空、nullは通常と同じふるまい
declare(strict_types=1) なし あり
返り値 エラー 返り値 エラー
'correct word' show ! correct word - show ! correct word -
999 999 - - TypeError
'' show ! - show ! -
null - TypeError - TypeError

所感

PHPの空、nullまわりの挙動がそもそもふわっとした理解だったのでまとめておいた。
標準関数によってはnullの挙動は中でよしなに変換しているかもなので使うときはいつもどおりリファレンスの確認が必要だなと感じた。


確認用プログラムと結果

プログラム
<?php
declare(strict_types=1);

$patterns[] = 'correct word';
$patterns[] = 999; //string以外
$patterns[] = ''; //空
$patterns[] = null; //空

foreach ($patterns as $pattern) {
    try {
        echo "\n\n\n input : $pattern \n";
        echo show($pattern);
    } catch (Throwable $e) {
        echo $e->__toString();
    }
}

function show(string $a): string
{
    return "show ! $a \n";
}

結果(型チェックなし)
achr@iMac PHP_practice % php strictTypesTest.php



 input : correct word 
show ! correct word 



 input : 999 //数値
show ! 999 



 input :  //空文字
show !  



 input :  //null
TypeError: Argument 1 passed to show() must be of the type string, null given, called in /Users/soachr/practice/PHP_practice/strictTypesTest.php on line 13 and defined in /Users/soachr/practice/PHP_practice/strictTypesTest.php:19
Stack trace:
#0 /Users/soachr/practice/PHP_practice/strictTypesTest.php(13): show(NULL)
#1 {main}%     
結果(型チェックあり)
soachr@iMac PHP_practice % php strictTypesTest.php



 input : correct word 
show ! correct word 



 input : 999 //数値
TypeError: Argument 1 passed to show() must be of the type string, int given, called in /Users/soachr/practice/PHP_practice/strictTypesTest.php on line 13 and defined in /Users/soachr/practice/PHP_practice/strictTypesTest.php:19
Stack trace:
#0 /Users/soachr/practice/PHP_practice/strictTypesTest.php(13): show(999)
#1 {main}


 input :  //空文字
show !  



 input :  //null
TypeError: Argument 1 passed to show() must be of the type string, null given, called in /Users/soachr/practice/PHP_practice/strictTypesTest.php on line 13 and defined in /Users/soachr/practice/PHP_practice/strictTypesTest.php:19
Stack trace:
#0 /Users/soachr/practice/PHP_practice/strictTypesTest.php(13): show(NULL)
#1 {main}%