douqiaosu0280 2012-11-16 13:53
浏览 47
已采纳

按位标志检测

I have problems with flag detection in 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));

But it returns:

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)

I'm new to bitwise operators, so it could be a problem with their definitions.

How do I fix this?

  • 写回答

1条回答 默认 最新

  • dpr26232 2012-11-16 13:55
    关注

    You are giving the values of the flags wrong; they are hexadecimal integer literals, so they should be

    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.
    

    You could also give them as decimal numbers (without the 0x prefix), although this can be misleading to someone who reads the code:

    const click       = 1;
    const mouseover   = 2;
    const mouseenter  = 4;
    const mouseout    = 8;
    const mouseleave  = 16;
    const doubleclick = 32;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算