什么使用单管'|' 在函数参数中吗?

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)


用Eddie Izzard的话说......国旗!

正如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)

  • +1这个伟大的帖子.我在解决这个问题时遇到了很多麻烦,但是你的解释和示例比我刚刚阅读PHP文档更容易理解它.非常感谢你. (5认同)
  • 很棒的解释和例子!+1 (4认同)
  • @cryptic无后顾之忧 - 毕竟搜索你无法命名的东西是相当棘手的 - 现在如果只有谷歌接受解释和例子的段落作为搜索词:) (3认同)

Ign*_*ams 16

你传递的参数是多个标志的按位OR .您可以随意使用操作员.

  • 感谢@Ignacio,记住并非所有SO人都是编程专家,甚至不知道从哪里开始编写文档. (8认同)