問題のコード
type_hint.php
<?php
class Main{
public function type_hint_boolean(boolean $arg){
var_dump($arg);
}
public function type_hint_integer(integer $arg){
var_dump($arg);
}
}
$main = new Main();
$main->type_hint_boolean(true);
$main->type_hint_integer(1);
出力
PHP Fatal error: Uncaught TypeError: Argument 1 passed to Main::type_hint_boolean() must be an instance of boolean, boolean given,
must be an instance of boolean, boolean given
booleanじゃなきゃいけないのにbooleanが渡されました???
ちなみにintegerの場合は以下のエラー
must be an instance of integer, integer given
解答
boolean
やinteger
はタイプヒントでは使えずbool
, int
で指定する必要がある
type_hint.php
<?php
class Main{
public function type_hint_bool(bool $arg){
var_dump($arg);
}
public function type_hint_int(int $arg){
var_dump($arg);
}
}
$main = new Main();
$main->type_hint_bool(true);
$main->type_hint_int(1);
出力
bool(true)
int(1)
解説
boolean
やinteger
を指定するとその名前のクラスのインスタンスのタイプヒントになってしまう
よって以下のコードは通る
type_hint.php
<?php
class Main{
public function type_hint_boolean(boolean $arg){
var_dump($arg);
}
public function type_hint_integer(integer $arg){
var_dump($arg);
}
}
class boolean{
}
class integer{
}
$main = new Main();
$main->type_hint_boolean(new boolean());
$main->type_hint_integer(new integer());
出力
object(boolean)#2 (0) {
}
object(integer)#2 (0) {
}
納得納得
参考
公式ドキュメント
PHP7調査(36)スカラ型のタイプヒントが書けるようになった
PHP: bool vs boolean type hinting