Why should I use bitwise/bitmask in PHP?

后端 未结 8 1829
时光取名叫无心
时光取名叫无心 2020-11-30 20:54

I am working on a user-role / permission system in PHP for a script.

Below is a code using a bitmask method for permissions that I found on phpbuilder.com.

B

相关标签:
8条回答
  • 2020-11-30 21:32

    Maybe it's just because I don't use bitmasks very often, but I find that in a language like PHP where developer productivity and code readability are more important than speed or memory usage (within limits, obviously), there's no real reason to use bitmasking.

    Why not instead create a class that tracks things like permissions, and logged in users, and so on? Let's call it Auth. Then, if you want to check that a user has a permission, you can create a method HasPermission. e.g.,

    if(Auth::logged_in() && Auth::currentUser()->hasPermission('read'))
        //user can read
    

    then if you want to check whether they have some combination of permissions:

    if(Auth::logged_in() && Auth::currentUser()->hasAllPermissions('read', 'write'))
        //user can read, and write
    

    or if you want to check whether they have any of a certain group of permissions:

    if(Auth::logged_in() && Auth::currentUser()->hasAnyPermissions('read', 'write'))
        //user can read, or write
    

    Of course, it may not be a bad idea to define constants, such as PERMISSION_READ, which you can just define to be the string 'read', and so on.

    I find this approach easier to read than bitmasks because the method names tell you exactly what it is you're looking for.

    0 讨论(0)
  • 2020-11-30 21:40

    Script checks which mask has been set in decimal. Maybe someone will need it:

    <?php
    
    $max = 1073741824;
    $series = array(0);
    $x = 1;
    $input = $argv[1]; # from command line eg.'12345': php script.php 12345
    $sum = 0;
    
    # generates all bitmasks (with $max)
    while ($x <= $max) {
        $series[] = $x;
        $x = $x * 2;
    }
    
    # show what bitmask has been set in '$argv[1]'
    foreach ($series as $value) {
        if ($value & $input) {
            $sum += $value;
            echo "$value - SET,\n";
        } else {
            echo "$value\n";
        }
    }
    
    # sum of set masks
    echo "\nSum of set masks: $sum\n\n";
    

    Output (php maskChecker.php 123):

    0
    1 - SET,
    2 - SET,
    4
    8 - SET,
    16 - SET,
    32 - SET,
    64 - SET,
    128
    256
    512
    1024
    2048
    4096
    8192
    (...)
    
    Sum of set mask: 123
    
    0 讨论(0)
提交回复
热议问题