开发者

PHP function flags, how?

开发者 https://www.devze.com 2023-01-14 11:09 出处:网络
开发者_如何学GoI\'m attempting to create a function with flags as its arguments but the output is always different with what\'s expected :
开发者_如何学Go

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?


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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号