LoginSignup
10
7

More than 3 years have passed since last update.

PHPのタイプヒントでbooleanを指定しているのにbooleanを指定しろと言われるんだが

Posted at

問題のコード

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

解答

booleanintegerはタイプヒントでは使えず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)

解説

booleanintegerを指定するとその名前のクラスのインスタンスのタイプヒントになってしまう
よって以下のコードは通る

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) {
}

納得納得 :smiley:

参考

公式ドキュメント
PHP7調査(36)スカラ型のタイプヒントが書けるようになった
PHP: bool vs boolean type hinting

10
7
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
10
7