Improve this PHP bitfield class for settings/permissions?

后端 未结 5 1436
名媛妹妹
名媛妹妹 2020-12-05 03:48

I have been trying to figure out the best way to use bitmask or bitfields in PHP for a long time now for different areas of my application for different user settings and pe

5条回答
  •  [愿得一人]
    2020-12-05 04:19

    Here is my proposal:

    value = $value;
        }
    
        public function getValue() {
            return $this->value;
        }
    
        public function get($n) {
                    return $this->value & $n;
        }
    
        public function set($n, $new=true) {
            $this->value |= $n;
        }
    
        public function clear($n) {
            $this->value &= ~$n;
        }
    
    }
    ?>
    

    As you can see, I used 1, 2, 4, 8, etc (powers of 2) to simplify the calculations. If you map one permission to one bit you have:

    0 0 0 0 0 0 0 1 = PERM_READ = 1
    0 0 0 0 0 0 1 0 = PERM_WRITE = 2
    0 0 0 0 0 1 0 0 = PERM_ADMIN = 4
    etc...
    

    Then you can use logic operations, for example you have this initially:

        0 0 0 0 0 0 0 1 = PERM_READ = 1
    

    If you want to add permissions to write, you only need to use the bitwise OR operator:

        0 0 0 0 0 0 0 1 = PERM_READ = 1
    OR  0 0 0 0 0 0 1 0 = PERM_WRITE = 2
    =   0 0 0 0 0 0 1 1 = both bits enabled R & W
    

    To remove one bit you have to use $value & ~$bit, for example remove the write bit:

        0 0 0 0 0 0 1 1 = both bits enabled R & W
    AND 1 1 1 1 1 1 0 1 = Bitwise negated PERM_WRITE
    =   0 0 0 0 0 0 0 1 = result, only the R bit
    

    Finally, if you want to test if one bit is enabled the operation you have to AND $value against the PERM_XXX you want to test:

        0 0 0 0 0 0 1 1 = both bits enabled R & W
    AND 0 0 0 0 0 0 1 0 = Want to test PERM_WRITE
    =   0 0 0 0 0 0 1 0 = result
    

    If the result is not zero you have the permission, otherwise you don't.

提交回复
热议问题