本文へスキップ
BecomeCoder

PHPのエラー · エラー6

TypeError: must be of type ... ― 型宣言と違う引数(実行時)

型宣言した引数に、違う型を渡すと出ます(PHP 7+ の型宣言)。

出るコード

<?php
function square(int $n): int { return $n * $n; }
echo square("abc");   // int を期待

エラーメッセージ

PHP Fatal error:  Uncaught TypeError: square(): Argument #1 ($n) must be of type int, string given

直し方

宣言した型に合う値を渡します。文字列を数値化するなら (int)"5"intval("5")