PHP:布尔与布尔类型提示

2022-01-19 00:00:00 type-hinting default-value boolean php

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

I've been trying to use type hinting more in PHP. Today I was writing a function that takes a boolean with a default parameter and I noticed that a function of the form

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

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

actually throws a fatal error:

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

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

:boolean false

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

Why is this? Is this similar to the wrapper classes in Java?

推荐答案

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

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

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);
?>

上面的例子会输出:

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

Fatal error: Uncaught TypeError: Argument 1 passed to test() must be an instance of boolean, boolean given

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

So in a nutshell, boolean is an alias for bool, and aliases don't work in type hints.
Use the "real" name: bool

类型提示之间没有相似之处类型转换.

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

Type hinting is something like that you are telling your function which type should be accepted.

类型转换是在类型之间切换".

允许的演员表是:

(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) 都是一样的.

In php type casting both (bool) and (boolean) are the same.

相关文章