PHP: boolean 与 boolean 类型提示

标签 php boolean default-value type-hinting

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

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

实际上抛出一个 fatal error :

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 的别名,别名在类型提示中不起作用。
使用“真实”名称:bool


Type Hinting 之间没有相似性和 Type Casting .

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

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

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

关于PHP: boolean 与 boolean 类型提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44009037/

相关文章:

php - 使用过滤器对 PHP 中的 MySQL 结果进行计数

php - 代码点火器缓存?

java - 测试给定字符串中的两对

objective-c - BOOL 的默认值

compiler-errors - VHDL - 分配默认值

php - 在 Controller 中使用 Goutte 和 Symfony2

c++ - 确定真/假

C#:枚举的默认值应该是 None 还是 Unknown?

javascript - 当 GraphQL 值可能为空时将其与 React 一起使用

php - withCount 与其他属性