按位标志检测

时间:2012-11-16 13:53:28

标签: php bit-manipulation flags

我在PHP中遇到标记检测问题。

<?php
class event
{
    const click = 0x1;
    const mouseover = 0x2;
    const mouseenter = 0x4;
    const mouseout = 0x8;
    const mouseleave = 0x16;
    const doubleclick = 0x32;

    public static function resolve($flags)
    {
        $_flags = array();

        if ($flags & self::click) $_flags[] = 'click';
        if ($flags & self::mouseover) $_flags[] = 'mouseover';
        if ($flags & self::mouseenter) $_flags[] = 'mouseenter';
        if ($flags & self::mouseout) $_flags[] = 'mouseout';
        if ($flags & self::mouseleave) $_flags[] = 'mouseleave';

        return $_flags;
    }
}

var_dump(event::resolve(event::click | event::mouseleave));

var_dump(event::resolve(event::mouseleave));

但它返回:

array (size=4)
  0 => string 'click' (length=5)
  1 => string 'mouseover' (length=9)
  2 => string 'mouseenter' (length=10)
  3 => string 'mouseleave' (length=10)


array (size=3)
  0 => string 'mouseover' (length=9)
  1 => string 'mouseenter' (length=10)
  2 => string 'mouseleave' (length=10)

我是bitwise运算符的新手,所以它们的定义可能会有问题。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:5)

你错误地给出了旗帜的价值;它们是十六进制整数文字,所以它们应该是

const click       = 0x01;
const mouseover   = 0x02;
const mouseenter  = 0x04;
const mouseout    = 0x08;
const mouseleave  = 0x10;
const doubleclick = 0x20;
// next values: 0x40, 0x80, 0x100, 0x200, 0x400, 0x800, 0x1000, etc.

您也可以将它们作为十进制数字给出(不带0x前缀),但这可能会误导读取代码的人:

const click       = 1;
const mouseover   = 2;
const mouseenter  = 4;
const mouseout    = 8;
const mouseleave  = 16;
const doubleclick = 32;