PHP表达式计算错误(?)值

时间:2014-09-02 18:12:20

标签: php

为什么变量$strange在以下代码段中评估为true

$strange = true and false;
var_dump($strange); // true

5 个答案:

答案 0 :(得分:3)

and&&的低precedence版本。

$strange = true and false;

相当于

($strange = true) and false;

你想要

$strange = (true and false);

或更合适

$strange = true && false;
andor之类的流控制语句之前,最好保留

breakreturn

foo()
   or throw new Exception('foo() returned an error.');

答案 1 :(得分:0)

PHP中的

andor具有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将被忽略。

相关问题