为什么变量$strange
在以下代码段中评估为true
?
$strange = true and false;
var_dump($strange); // true
答案 0 :(得分:3)
and
是&&
的低precedence版本。
$strange = true and false;
相当于
($strange = true) and false;
你想要
$strange = (true and false);
或更合适
$strange = true && false;
在and
或or
之类的流控制语句之前,最好保留 break
和return
。
foo()
or throw new Exception('foo() returned an error.');
答案 1 :(得分:0)
and
和or
具有LOWER运算符优先级,然后是&&
和||
。您的代码正在评估为
($strange = true) and false;
这两个可行:
$strange = true && false;
$strange = (true and false);
答案 2 :(得分:0)
请参阅documentation:
// The constant true is assigned to $h and then false is executed then and its
// value is and'd with the results of the assignment.
// Acts like: (($h = true) and false)
$h = true and false;
以上示例直接从那里开始,并完全符合您的问题。
答案 3 :(得分:0)
我没有PHP专家,但这似乎是一个简单逻辑的问题......
表达式var_dump($strange);
评估并输出 第一个 参数。
答案 4 :(得分:0)
正如documentation所说:
// foo() will never get called as those operators are short-circuit
$a = (false && foo());
$b = (true || foo());
$c = (false and foo());
$d = (true or foo());
和
// The constant true is assigned to $h and then false is ignored
// Acts like: (($h = true) and false)
$h = true and false;
因此false
将被忽略。