逻辑运算符和优先级
Logical Operators and Precedence
所以我只是做了一些随机测试并了解优先级和 || 和 or 运算符的基本原理,但我有无法理解为什么 $f 发生变化:
$f = 0 || 1;
if ($f === 1){
echo "TRUE - $f";
}else{
echo "FALSE - $f";
}
$f = 0 or 1;
if ($f === 0){
echo "TRUE - $f";
}else{
echo "FALSE - $f";
}
感谢您的一些见解。
您所做的与以下内容相同:
if (($f = 0) or 1){
// $f is being assigned the value 0, and the condition evaluates 0 or 1,
// 1 being equivalent to true, the condition is always true.
echo "TRUE - $f";
}else{
echo "FALSE - $f";
}
和
if ($f = (0 || 1)){ // which gives $f = true which returns true
echo "TRUE - $f";
}else{
echo "FALSE - $f";
}
如果你想检查 $f 是否等于一个值或另一个你会做
if ($f === 0 or $f === 1)
请注意,在 php 中,默认情况下 int 1 将被评估为 bool true,除非您进行严格比较 === 或 !==
总是计算到 True
是正常的。原因是 OR 意味着如果其中一个值是 True 它将采用这个值。
更新您的新问题:
答案是“||”优先级高于 "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;
您可以在 PHP 手册网站 here 上了解更多信息,我找到了这个示例
问题在这里:"if ($f = 0 or 1){" :
"=" 意味着你给变量 $f 值 0
你应该使用:
- "==" : 检查值是否相等
- "===" : 检查左变量是否与右变量相同(值、类型等)
所以我只是做了一些随机测试并了解优先级和 || 和 or 运算符的基本原理,但我有无法理解为什么 $f 发生变化:
$f = 0 || 1;
if ($f === 1){
echo "TRUE - $f";
}else{
echo "FALSE - $f";
}
$f = 0 or 1;
if ($f === 0){
echo "TRUE - $f";
}else{
echo "FALSE - $f";
}
感谢您的一些见解。
您所做的与以下内容相同:
if (($f = 0) or 1){
// $f is being assigned the value 0, and the condition evaluates 0 or 1,
// 1 being equivalent to true, the condition is always true.
echo "TRUE - $f";
}else{
echo "FALSE - $f";
}
和
if ($f = (0 || 1)){ // which gives $f = true which returns true
echo "TRUE - $f";
}else{
echo "FALSE - $f";
}
如果你想检查 $f 是否等于一个值或另一个你会做
if ($f === 0 or $f === 1)
请注意,在 php 中,默认情况下 int 1 将被评估为 bool true,除非您进行严格比较 === 或 !==
总是计算到 True
是正常的。原因是 OR 意味着如果其中一个值是 True 它将采用这个值。
更新您的新问题:
答案是“||”优先级高于 "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;
您可以在 PHP 手册网站 here 上了解更多信息,我找到了这个示例
问题在这里:"if ($f = 0 or 1){" :
"=" 意味着你给变量 $f 值 0
你应该使用:
- "==" : 检查值是否相等
- "===" : 检查左变量是否与右变量相同(值、类型等)