Set permissions in binary

前端 未结 5 2004
说谎
说谎 2020-12-29 16:06

I saw in school a system that set permissions using binary string.

Let\'s say 101001 = 41

So :

  • 1 can be permission to page 1
  • 2 can b
5条回答
  •  清酒与你
    2020-12-29 16:45

    Sounds like you're talking about bits and bit-wise operators. This easiest way to set this up is to define constants for every permission

    const POST   = 1;
    const DELETE = 2;
    const UPDATE = 4;
    const READ   = 8;
    

    Once you have these defined it's easy to make comparisons using the bitwise operators:

    $userValue = '1101';
    
    if ($userValue & self::POST) {
      echo 'Can Post';
    }
    
    if ($userValue & self::DELETE) {
      echo 'Can Delete';
    }
    
    if ($userValue & self::UPDATE) {
      echo 'Can Update';
    }
    
    if ($userValue & self::READ) {
      echo 'Can Read';
    }
    

    This is how many of PHP's own constants work. If you've ever set the error reporting using something like E_ALL & E_DEPRECATED you're actually working with binary numbers.

提交回复
热议问题