PHP:bool与boolean类型提示 [英] PHP: bool vs boolean type hinting

查看:448
本文介绍了PHP:bool与boolean类型提示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这是为什么?这类似于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必须是boolean(给定为boolean)的实例

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 Type Casting .

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

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

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

Type casting is to "switching" between types.

允许的演员为:

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 类型转换中,(布尔)和(布尔)都是相同的.

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

这篇关于PHP:bool与boolean类型提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆