开发者

PHP: Why typecast with !!$var instead of (boolean)$var?

开发者 https://www.devze.com 2022-12-15 09:35 出处:网络
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 me

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.

The double exclamation mark is something I've only heard of in JavaScript, which doesn't have boolean typecasting. Is it no开发者_如何学Pythonrmal to see it used in PHP as well?


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

var booleanValue = Boolean(otherValueType);

This is equivalent to:

var booleanValue = !!otherValueType;

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.


Neither of those is common in PHP because they're unnecessary.

If you can do !!, you can just as well use it where a boolean expression is necessary (while, if, &&, etc.).

0

精彩评论

暂无评论...
验证码 换一张
取 消