我在PHP中有以下几行代码:
$a = $b && $c || $d;
和
$a = $b AND $c || $d;
和
$a = $b && $c OR $d;
和
$a = $b AND $c OR $d;
每一行都使用不同的运算符,因此它是不同的,如果是,那有什么区别? 它是如何执行的?
答案 0 :(得分:3)
执行这些运算符的顺序不同。
// 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;
答案 1 :(得分:0)
答案 2 :(得分:0)
作为short-circuit, they are the same.
&& means
和,
|| means
或`,它们的行为相同:
// 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;