PHP函数的标志,怎么样? [英] PHP function flags, how?

查看:127
本文介绍了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 LT; 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆