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

问题描述 投票:71回答:2

以下面的代码为例:

phpinfo(INFO_MODULES | INFO_ENVIRONMENT | INFO_VARIABLES);

正在使用单个参数,但我提供了由单个管道符号分隔的选项列表。

  • 函数中的参数值究竟发生了什么?
  • 我可以在自己的功能中使用相同的东西吗?
  • 是这样的,并且有什么好处,而不是说传递一个数组呢?
php function arguments bitwise-operators
2个回答
117
投票

Bitwise operators

按位运算符修改所涉及的值的位。按位OR基本上将左右参数的每个位OR运算在一起。例如:

5 | 2

将转换为位/二进制为:

101 | 10

这将导致:

111

因为:

1 || 0 = 1
0 || 1 = 1
1 || 0 = 1

并且作为一个整数,它代表7,如果你得到的正是你得到的:

echo 5 | 2;

In the words of Eddie Izzard... Flag!

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

16
投票

你传递的是multiple flags的按位OR的参数。您可以随意使用操作员。

© www.soinside.com 2019 - 2024. All rights reserved.