【问题标题】:PHP: bool vs boolean type hintingPHP:布尔与布尔类型提示
【发布时间】:2017-10-15 23:34:57
【问题描述】:

我一直在尝试在 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);

给出完全相同的输出

:boolean false

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

【问题讨论】:

  • 检查the manual有效支持类型
  • 使用bool 进行类型提示。

标签: php boolean default-value type-hinting


【解决方案1】:

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

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

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

上面的例子会输出:

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

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


Type HintingType 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) 都是一样的。

【讨论】:

  • no similarity between Type Hinting and Type Casting -- 标量类型提示,参数和返回类型,都执行类型转换。换句话说:(function():bool { return 1; })() === true
猜你喜欢
  • 2016-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-08
  • 1970-01-01
  • 2011-01-01
  • 1970-01-01
相关资源
最近更新 更多