PHP:bool 与布尔类型提示

问题描述 投票:0回答:1

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

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

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

带有类类型提示的参数的默认值只能为 NULL

虽然是类似形式的函数

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

没有。然而,两者

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

给出完全相同的输出

:布尔值 false

这是为什么呢?这和Java中的包装类类似吗?

php boolean default-value type-hinting
1个回答
108
投票

https://www.php.net/manual/en/language.types.declarations.php#language.types.declarations.base.scalar

警告
不支持上述标量类型的别名。相反,它们被视为类或接口名称。例如,使用 boolean 作为参数或返回类型将需要一个属于类或接口 boolean 实例的参数或返回值,而不是 bool 类型:

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

上面的例子将输出:

致命错误:未捕获类型错误:传递给 test() 的参数 1 必须是布尔值的实例,给定布尔值

所以简而言之,

boolean
bool
的别名,而别名在类型提示中不起作用。
使用“真实”名称:bool


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

类型提示就像你告诉你的函数应该接受哪种类型。

类型转换是在类型之间“切换”。

允许的演员阵容有:

(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) 是相同的。

© www.soinside.com 2019 - 2024. All rights reserved.