位运算符
位运算符修改所涉及的值的位。按位 OR 基本上将左右参数的每一位进行或运算。例如:
5 | 2
将转换为位/二进制:
101 | 10
这会导致:
111
因为:
1 || 0 = 1
0 || 1 = 1
1 || 0 = 1
作为一个表示 7 的整数,这正是你得到的结果:
echo 5 | 2;
用 Eddie Izzard 的话来说......国旗!
正如 Ignacio 所说,这在 PHP(和其他语言)中最常用于组合多个标志的方式。每个标志通常定义为一个常量,其值通常设置为一个整数,表示不同偏移量的一位:
define('FLAG_A', 1); /// 0001
define('FLAG_B', 2); /// 0010
define('FLAG_C', 4); /// 0100
define('FLAG_D', 8); /// 1000
然后当你 OR 这些一起时,它们会根据自己的位偏移量进行操作,并且永远不会发生冲突:
FLAG_A | FLAG_C
翻译为:
1 | 100
所以你最终打开了:
101
代表整数5。
那么所有代码必须做的——将对设置的不同标志做出反应的代码——如下(使用按位AND):
$combined_flags = FLAG_A | FLAG_C;
if ( $combined_flags & FLAG_A ) {
/// do something when FLAG_A is set
}
if ( $combined_flags & FLAG_B ) {
/// this wont be reached with the current value of $combined_flags
}
if ( $combined_flags & FLAG_C ) {
/// do something when FLAG_C is set
}
归根结底,它只是通过命名常量使事情更容易阅读,并且通常通过依赖整数值而不是字符串或数组来更优化。使用常量的另一个好处是,如果它们在使用时输入错误,编译器可以更好地告知并发出警告......如果使用字符串值,它无法知道有什么问题。
define('MY_FLAG_WITH_EASY_TYPO', 1);
my_function_that_expects_a_flag( MY_FLAG_WITH_EASY_TPYO );
/// if you have strict errors on the above will trigger an error
my_function_that_expects_a_flag( 'my_string_with_easy_tpyo' );
/// the above is just a string, the compiler knows nowt with
/// regard to it's correctness, so instead you'd have to
/// code your own checks.