2013-05-21 40 views
2

为什么评估是真的? $test = true and false;PHP中的&&与运营商之间的差异

而这不是吗? $test = (true and false);

随着& &操作它既计算为false,这是我也期望与和运营商。显然它们不可互换,除了它们具有不同的优先顺序。

+0

http://es1.php.net/manual/en/language.operators.precedence.php –

+1

请参阅http://stackoverflow.com/questions/2803321/and-vs-as-operator – Luca

+0

我在另一个问题中找到了答案:http://stackoverflow.com/a/2803576/1630609 –

回答

4

他们除了Precedence

&&>=>在优先级表and一样的,所以你的第一个例子是等价于:($test = true) and false;

6

“& &”比“和”

更大的优先级
// The result of the expression (true && false) is assigned to $g 
// Acts like: ($g = (true && false)) 
$g = true && false; 

// The constant true is assigned to $h and then false is ignored 
// Acts like: (($h = true) and false) 
$h = true and false; 

var_dump($g, $h); 

打印假,真

+0

这对于在没有parentesis的同一行中进行赋值和比较很有用:'if($ a = true和$ b)'将'true'赋值给'$ a'然后解析逻辑运算。如果表达式被评估为'true',则可以在'if'块范围中使用'$ a'的值。这相当于:'if(($ a = true)&& $ b)'。 –

+0

简短而明确的答案。这是我们在堆栈溢出中需要的。 – Stranger