在 PHP 中,逻辑运算符如何与非布尔值一起使用?
在其他编程语言(Python、Ruby、Scheme)中,我习惯做这样的事情:
$foo = $cat && $dog;
$bar = $fruit || $vegetable;
如果 $cat 为 null,则将 $foo 分配给 $dog,如果 $fruit 不为 null,则将 $bar 分配给 $fruit 。 我似乎记得因为在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这对你有用吗?
$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.
在 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.