gpt4 book ai didi

php - 在函数参数中使用单管道 '|' 有什么作用?

转载 作者:IT老高 更新时间:2023-10-28 11:55:51 29 4
gpt4 key购买 nike

以下面的代码为例:

phpinfo(INFO_MODULES | INFO_ENVIRONMENT | INFO_VARIABLES);

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

  • 函数中的参数值究竟发生了什么?
  • 我可以在自己的函数中使用相同的东西吗?
  • 是这样吗,与传递数组相比,这样做有什么好处吗?

最佳答案

位运算符

位运算符修改所涉及的值的位。按位 OR 基本上将左右参数的每一位 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。

那么所有的代码都必须做——将对设置的不同标志使用react的代码——如下(使用按位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.

关于php - 在函数参数中使用单管道 '|' 有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13811922/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com