php为什么或运算符返回0为真

时间:2014-10-22 21:25:47

标签: php

在以下代码中:

$a = 0 or 1;
$b = 0 || 1; 
echo "$a, $b"; // 0, 1

为什么$a等于零,我认为or||在PHP中可以互换? or语句究竟发生了什么,使其返回0

我会假设两个结果都是1,使其回显1, 1

3 个答案:

答案 0 :(得分:8)

or的优先级低于=,优先级低于""

所以你的代码相当于:

($a = 0) or 1;
$b = (0 || 1); 

请参阅PHP手册中的precedence table

答案 1 :(得分:0)

这是因为PHP中的优先规则。赋值=运算符的优先级低于逻辑||运算符,但优先级高于逻辑OR运算符。见这里:http://php.net/manual/en/language.operators.precedence.php

答案 2 :(得分:0)

由于优先顺序

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

http://php.net/manual/en/language.operators.logical.php