我一直在尝试在 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
所以简而言之,boolean
是bool
的别名,别名在类型提示中不起作用。
使用“真实”名称: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/