我有2个布尔变量$products_changed
和$address_changed
。
我想为每种状态显示一个视觉指示器:
products_changed
为真address_changed
为真目前我正在做:
if ($products_changed && $address_changed) //if both have changed
{
//visual indicator for both
}
elseif ($products_changed) //only products changed
{
//visual indicator for products changed
}
elseif ($address_changed) //only address changed
{
//visual indicator for address changed
}
我需要一个可以应用的逻辑/数学运算符,并且在结果中包含两者是否为真或两者都为假。但是,如果只有一个是真的 - 我需要知道哪一个(第一个或第二个)。
我想重构我的代码:
const BOTH_CHANGED = 1, PRODUCTS_CHANGED = 2, ADDRESS_CHANGED = 3;
//The numbers 1,2,3 are arbitrary, could be any numbers.
$visual_indicator = $products_changed **SOME_OPERATOR** $address_changed;
switch( $visual_indicator) {
case BOTH_CHANGED: //display visual indicator for both changed
break;
case PRODUCTS_CHANGED: //display visual indicator for products changed
break;
case ADDRESS_CHANGED: //display visual indicator for address changed
break;
}
我意识到我能做到:
$visual_indicator = (int)$products_changed * 10 + (int)$address_changed;
//11 will be both changed, 10 will be products changed, 1 will be address changed
然而,我正在寻找一个更优雅,可能是原生的运营商。 这对于减少代码冗余和可读性都很重要(这当然是我的代码的简化版本,所以在我自己的项目中这会有更好的含义)。
帮助&我们将不胜感激。感谢。
答案 0 :(得分:1)
对于这样的事情,我使用按位运算符。如下所示:
<?php
// shift each option by 1
define('A', 1);
define('B', 1<<1);
define('C', 1<<2);
// combine opitons with bitwise or (|)
$c = A | C;
// compare with or'ed values to find the combination
switch ($c) {
case A:
print "A only\n";
break;
case A|B:
print "A and B\n";
break;
case A|C:
print "A and C\n";
break;
}
// use bitwise and (&) to check if an option is present
if ($c & A) print "Has A\n";
if ($c & B) print "Has B\n";
if ($c & C) print "Has C\n";