PHP:为什么使用!! $ var而不是(boolean)$ var进行类型转换? [英] PHP: Why typecast with !!$var instead of (boolean)$var?

查看:66
本文介绍了PHP:为什么使用!! $ var而不是(boolean)$ var进行类型转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两个都将确保$ var是布尔值,但后者似乎更清楚.双重感叹号(!!)的字体较短,但不太清晰,更容易引起混淆.更不用说努力进行搜索以获得答案了.

Both of these will ensure than $var is a boolean value, but the latter seems more clear. The double exclamation mark (!!) is shorter to type but less clear, and more likely to cause confusion. Not to mention hard to run a search on to get answers.

双重感叹号是我在JavaScript中仅听说的一种,它没有布尔类型转换.看到它也在PHP中使用是否正常?

The double exclamation mark is something I've only heard of in JavaScript, which doesn't have boolean typecasting. Is it normal to see it used in PHP as well?

推荐答案

这在JavaScript中有效,尽管从技术上讲不是"cast",但可以达到相同的效果:

This is valid in JavaScript, although not technically a "cast", it achieves the same effect:

var booleanValue = Boolean(otherValueType);

这等效于:

var booleanValue = !!otherValueType;

我发现在处理传入参数时最好这样做,以阐明一个原意将值设为布尔值.在检查真实性"时,无需使用PHP或JavaScript进行类型转换.请记住,空字符串等效于PHP中的 false 和JavaScript中的 true .

I find it is good to do this when processing incoming parameters, to clarify that one intended a value to be a boolean. When checking for "truthiness", there is no need to typecast in either PHP or JavaScript. Just remember that an empty string is equivalent to false in PHP and true in JavaScript.

因此,要回答您的问题,无论哪种语言都可以,这只是个人风格的选择.

So, to answer your question, either is fine in either language, it is simply a personal style choice.

这篇关于PHP:为什么使用!! $ var而不是(boolean)$ var进行类型转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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