PHP or是一个奇怪的关键字.这是一个让我困惑的代码片段:
echo 0 or 1; // prints 1
$foo = (0 or 1);
echo $foo; // prints 1
$foo = 0 or 1;
echo $foo; // prints 0 for some reason
Run Code Online (Sandbox Code Playgroud)
为什么最后一个打印0而不是1?
Pek*_*ica 21
这是因为运营商的优先级不同.在第三种情况下,首先处理分配.它将被解释为:
($foo = 0) or 1;
Run Code Online (Sandbox Code Playgroud)
该||运营商有不同的优先级.如果你使用
$foo = 0 ||1;
Run Code Online (Sandbox Code Playgroud)
它会像你期望的那样工作.
请参阅逻辑运算符手册
不,我不会,那是因为运营商优先:
$foo = 0 or 1;
// is same as
($foo = 0) or 1;
// because or has lower precedence than =
$foo = 0 || 1;
// is same as
$foo = (0 || 1);
// because || has higher precedence than =
// where is this useful? here:
$result = mysql_query() or die(mysql_error());
// displays error on failed mysql_query.
// I don't like it, but it's okay for debugging whilst development.
Run Code Online (Sandbox Code Playgroud)