PHP 函数标志,如何? [英] PHP function flags, how?
本文介绍了PHP 函数标志,如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建一个以标志为参数的函数,但输出总是与预期不同:
I'm attempting to create a function with flags as its arguments but the output is always different with what's expected :
define("FLAG_A", 1);
define("FLAG_B", 4);
define("FLAG_C", 7);
function test_flags($flags) {
if($flags & FLAG_A) echo "A";
if($flags & FLAG_B) echo "B";
if($flags & FLAG_C) echo "C";
}
test_flags(FLAG_B | FLAG_C); # Output is always ABC, not BC
我该如何解决这个问题?
How can I fix this problem?
推荐答案
标志必须是 2 的幂才能正确地按位或组合在一起.
Flags must be powers of 2 in order to bitwise-or together properly.
define("FLAG_A", 0x1);
define("FLAG_B", 0x2);
define("FLAG_C", 0x4);
function test_flags($flags) {
if ($flags & FLAG_A) echo "A";
if ($flags & FLAG_B) echo "B";
if ($flags & FLAG_C) echo "C";
}
test_flags(FLAG_B | FLAG_C); # Now the output will be BC
对常量值使用十六进制表示法对程序的行为没有影响,但这是向程序员强调这些值构成位字段.另一种方法是使用移位:1<<0
、1<<1
、1<<2
、&c.
Using hexadecimal notation for the constant values makes no difference to the behavior of the program, but is one idiomatic way of emphasizing to programmers that the values compose a bit field. Another would be to use shifts: 1<<0
, 1<<1
, 1<<2
, &c.
这篇关于PHP 函数标志,如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文