2013-05-21 39 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