我已经挖掘了一下,但我似乎找不到一个简单的答案来解释为什么你不能编写类似的代码
<?php
$x=2;
if(1<$x<3) {
echo "Win!";
} else {
echo "Lose!";
}
?>
我的直觉说因为 PHP 从左向右读取,所以它评估语句的前半部分 (< code>1<$x) 然后只看到 <3 这是没有意义的。我只是希望有人确认(或反驳)情况确实如此,并且任何时候您在 PHP 中提供条件时都必须将每个条件分开。我不知道这是否会被称为逻辑或语法或其他东西,但你可以在其他上下文(如SAS)中编写这样的表达式并对它们进行评估,所以我想了解为什么你不能在PHP。谢谢!
I've dug around a bit, but I can't seem to find a simple answer as to why you can't code something like
<?php
$x=2;
if(1<$x<3) {
echo "Win!";
} else {
echo "Lose!";
}
?>
My gut says that because PHP reads left-right, it evaluates the first half of the statement (1<$x
) and then just sees <3 which is meaningless. I'd just like someone to confirm (or refute) that this is the case and that any time you're providing conditions in PHP you have to separate out each one. I don't know if this would be called logic or syntax or something else, but you can write expressions like these in other contexts (like SAS) and have them evaluated, so I'd just like to understand why you can't in PHP. Thanks!
发布评论
评论(2)
PHP 计算
1 < $x
,然后将其结果与3
进行比较。换句话说,如果添加括号,PHP 会将其视为((1 < $x) < 3)
。如果
1 < $x
为 true,则比较变为1 < 3
;如果为 false,则为0 < 3.
.这是由于类型转换(从布尔值到整数)造成的。两者的计算结果均为 true,因此 if 条件始终满足。你确实必须这样写:
PHP evaluates
1 < $x
, then compares the result of that to3
. In other words, if you add brackets, PHP sees it as((1 < $x) < 3)
.If
1 < $x
is true, the comparison becomes1 < 3
; if false, it's0 < 3
. This is due to type conversion (from boolean to integer). Both evaluate to true, so the if condition is always satisfied.You'll indeed have to write it like this instead:
<
和>
运算符计算结果为布尔值。这是从 C 继承下来的设计选择。The
<
and>
operators evaluate to boolean values. It was a design choice carried over from C.