2013-11-25 4 views
-1

У меня есть следующие строки кода в PHP:В чем разница между кодом

$a = $b && $c || $d; 

и

$a = $b AND $c || $d; 

и

$a = $b && $c OR $d; 

и

$a = $b AND $c OR $d; 

В каждой строке используются разные операторы, так что это разные, и если да, в чем разница? Как это выполняется?

+0

разные формы имеют разный приоритет. – Jon

+0

Возможный дубликат ['AND' vs '&&' as operator] (http://stackoverflow.com/questions/2803321/and-vs-as-operator) – glomad

ответ

3

Разница в том, как выполняются эти операторы.

Operator Precedence

// 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; 
0

Как short-circuit, they are the same. & & means И , || means Or`, они действуют одинаково:

// 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()); 

В другой стороны, || имеет больший приоритет, чем or,

// The result of the expression (false || true) is assigned to $e 
// Acts like: ($e = (false || true)) 
$e = false || true; 

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

То же самое с && и and:

// 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; 
Смежные вопросы