PHP: bool vs boolean type hinting

≯℡__Kan透↙ 提交于 2019-11-30 11:00:25
Niet the Dark Absol

http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration

Warning
Aliases for the above scalar types are not supported. Instead, they are treated as class or interface names. For example, using boolean as a parameter or return type will require an argument or return value that is an instanceof the class or interface boolean, rather than of type bool:

<?php
function test(boolean $param) {}
test(true);
?>

The above example will output:

Fatal error: Uncaught TypeError: Argument 1 passed to test() must be an instance of boolean, boolean given

So in a nutshell, boolean is an alias for bool, and aliases don't work in type hints.
Use the "real" name: bool


There are no similarity between Type Hinting and Type Casting.

Type hinting is something like that you are telling your function which type should be accepted.

Type casting is to "switching" between types.

The casts allowed are:

(int), (integer) - cast to integer
(bool), (boolean) - cast to boolean
(float), (double), (real) - cast to float
(string) - cast to string
(array) - cast to array
(object) - cast to object
(unset) - cast to NULL (PHP 5)

In php type casting both (bool) and (boolean) are the same.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!