Jim*_*y P 47 php boolean default-value type-hinting
我一直在尝试在PHP中使用更多类型提示.今天我正在编写一个带有默认参数的布尔值的函数,我注意到了表单的一个函数
function foo(boolean $bar = false) {
var_dump($bar);
}
Run Code Online (Sandbox Code Playgroud)
实际上会抛出一个致命的错误:
具有类类型提示的参数的默认值只能为NULL
虽然是类似形式的功能
function foo(bool $bar = false) {
var_dump($bar);
}
Run Code Online (Sandbox Code Playgroud)
才不是.但是,两者都有
var_dump((bool) $bar);
var_dump((boolean) $bar);
Run Code Online (Sandbox Code Playgroud)
给出完全相同的输出
:布尔值false
为什么是这样?这类似于Java中的包装类吗?
Nie*_*sol 59
http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration
警告
不支持上述标量类型的别名.相反,它们被视为类或接口名称.例如,使用boolean作为参数或返回类型将需要一个参数或返回值,该值是类或接口boolean的实例,而不是bool类型:Run Code Online (Sandbox Code Playgroud)<?php function test(boolean $param) {} test(true); ?>上面的例子将输出:
致命错误:未捕获的TypeError:传递给test()的参数1必须是boolean的实例,给定boolean
简而言之,boolean是别名bool,而别名在类型提示中不起作用.
使用"真实"名称:bool
Type Hinting和之间没有相似之处Type Casting.
类型提示类似于你告诉你的功能应该接受哪种类型.
类型转换是在类型之间"切换".
允许的演员阵容是:
Run Code Online (Sandbox Code Playgroud)(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)都是相同的.