cry*_*c ツ 75 php arguments function bitwise-operators
以下面的代码为例:
phpinfo(INFO_MODULES | INFO_ENVIRONMENT | INFO_VARIABLES);
Run Code Online (Sandbox Code Playgroud)
正在使用单个参数,但我提供了由单个管道符号分隔的选项列表.
先感谢您.
Peb*_*bbl 119
按位运算符修改所涉及的值的位.按位OR基本上将左右参数的每个位OR 运算在一起.例如:
5 | 2
Run Code Online (Sandbox Code Playgroud)
将转换为位/二进制为:
101 | 10
Run Code Online (Sandbox Code Playgroud)
这将导致:
111
Run Code Online (Sandbox Code Playgroud)
因为:
1 || 0 = 1
0 || 1 = 1
1 || 0 = 1
Run Code Online (Sandbox Code Playgroud)
并且作为一个整数,它代表7,如果你得到的正是你得到的:
echo 5 | 2;
Run Code Online (Sandbox Code Playgroud)
正如Ignacio所述,这最常用于PHP(和其他语言)中,作为组合多个标志的方法.每个标志通常定义为一个常量,其值通常设置为一个整数,该整数仅代表不同偏移量的一个位:
define('FLAG_A', 1); /// 0001
define('FLAG_B', 2); /// 0010
define('FLAG_C', 4); /// 0100
define('FLAG_D', 8); /// 1000
Run Code Online (Sandbox Code Playgroud)
然后,当你将OR它们放在一起时,它们每个都按照自己的位偏移运行,永远不会碰撞:
FLAG_A | FLAG_C
Run Code Online (Sandbox Code Playgroud)
翻译为:
1 | 100
Run Code Online (Sandbox Code Playgroud)
所以你最终开启了:
101
Run Code Online (Sandbox Code Playgroud)
代表整数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
}
Run Code Online (Sandbox Code Playgroud)
在一天结束时,它只是通过命名常量使事情更容易阅读,并且通常依靠整数值而不是字符串或数组更优化.使用常量的另一个好处是,如果它们在使用时输入错误,编译器处于更好的状态告诉并发出警告......如果使用字符串值,则无法知道任何错误.
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.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19698 次 |
| 最近记录: |