在 PHP 中,逻辑运算符如何与非布尔值一起使用?

发布于 2024-07-27 13:42:24 字数 478 浏览 2 评论 0原文

在其他编程语言(Python、Ruby、Scheme)中,我习惯做这样的事情:

$foo = $cat && $dog;
$bar = $fruit || $vegetable;

如果 $cat 为 null,则将 $foo 分配给 $dog,如果 $fruit 不为 null,则将 $bar 分配给 $fruit 。 我似乎记得因为在 PHP 中做这样的事情而被烧伤,而且我从来没有确切地了解逻辑运算符如何处理非布尔操作数。 有人可以解释或指出我正确的方向吗? 我尝试阅读官方文档中的以下页面,但它不处理非布尔值:

https://www.php.net/manual/en/language.operators.logic.php

In other programming languages (Python, Ruby, Scheme), I'm used to doing things like

$foo = $cat && $dog;
$bar = $fruit || $vegetable;

I would expect that $foo would get assigned to $dog if $cat were null, and $bar to $fruit if $fruit were NOT null. I seem to recall getting burned for doing things like this in PHP, and I've never learned exactly how logical operators handle non-boolean operands. Can someone explain or point me in the right direction? I tried reading the following page in the official docs, but it doesn't deal with non-booleans:

https://www.php.net/manual/en/language.operators.logical.php

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

眼波传意 2024-08-03 13:42:25

这对你有用吗?

$foo = $cat ? $猫:$狗;

第一个 $cat 将根据已知规则转换为布尔值。 如果为真,那么 $foo 将是 $cat,否则是 $dog。

Would this work for you?

$foo = $cat ? $cat : $dog;

The first $cat will get turned into a Boolean based on known rules. If it's true then $foo will be $cat otherwise it's $dog.

冷心人i 2024-08-03 13:42:24

在 PHP 中,布尔比较的结果始终是布尔值,操作数被强制为布尔值。

https://www.php.net/manual/en/language。 types.boolean.php

解释了哪些值在被强制转换时将变为 true 或 false。

In PHP the result of a boolean comparison is always a boolean, the operands are coerced to boolean.

https://www.php.net/manual/en/language.types.boolean.php

explains which values, when they are coerced, will becomes true or false.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文