PHP: bool vs boolean 类型提示

PHP: bool vs boolean type hinting

我一直在尝试在 PHP 中更多地使用类型提示。今天我正在写一个函数,它接受一个带有默认参数的布尔值,我注意到

形式的函数
function foo(boolean $bar = false) {
    var_dump($bar);
}

实际上抛出一个致命错误:

Default value for parameters with a class type hint can only be NULL

而类似形式的函数

function foo(bool $bar = false) {
    var_dump($bar);
}

没有。然而,

var_dump((bool) $bar);
var_dump((boolean) $bar);

给出完全相同的输出

:boolean false

这是为什么?这类似于 Java 中的包装器 类 吗?

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

所以简而言之,booleanbool 的别名,别名在类型提示中不起作用。
使用 "real" 名称:bool


Type Hinting and Type Casting之间没有相似之处。

类型提示 类似于您告诉您的函数应该接受哪种类型。

类型转换是在类型之间"switching"。

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)

在 php 类型转换中 (bool) 和 (boolean) 是相同的。