Advertisement
jasondavis

Bitmask Settings

Jul 25th, 2011
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.89 KB | None | 0 0
  1. <?php
  2. //Bit class for settings
  3. abstract class BitField {
  4.  
  5.     private $value;
  6.  
  7.     public function __construct($value=0) {
  8.         $this->value = $value;
  9.     }
  10.  
  11.     public function getValue() {
  12.         return $this->value;
  13.     }
  14.  
  15.     public function get($n) {
  16.         return ($this->value & $n) == $n;
  17.     }
  18.  
  19.     //turns a setting Bit to ON/TRUE
  20.     public function set($n) {
  21.         $this->value |= $n;
  22.     }
  23.  
  24.     //turns a setting Bit to OFF/FALSE
  25.     public function clear($n) {
  26.         $this->value &= ~$n;
  27.     }
  28. }
  29.  
  30. //User settings using bits and the BitField class... super cool
  31. class UserPrivacySettings extends BitField
  32. {
  33.     const PRIVACY_EMAIL = 1;
  34.     const PRIVACY_NAME = 2;
  35.     const PRIVACY_ADDRESS = 4;
  36.     const PRIVACY_PHONE = 8;
  37.     const PRIVACY_ALL = 15;
  38. }
  39.  
  40.  
  41. $bf = new UserPrivacySettings();
  42.  
  43. //Turning PRIVACY_EMAIL Setting to ON/TRUE using Bits
  44. $bf->set(UserPrivacySettings::PRIVACY_EMAIL);
  45.  
  46. // Get PRIVACY_EMAIL Setting Bit value
  47. if ($bf->get(UserPrivacySettings::PRIVACY_EMAIL))
  48. {
  49.     echo '<br><font color="green">PRIVACY_EMAIL Setting is ON/TRUE</font><br>';
  50. }else{
  51.     echo '<br><font color="red">PRIVACY_EMAIL Setting is OFF/FALSE</font><br>';
  52. }
  53.  
  54.  
  55. // Turning PRIVACY_EMAIL Setting Bit ZOFF/FALSE
  56. $bf->clear(UserPrivacySettings::PRIVACY_EMAIL);
  57.  
  58. // Get PRIVACY_EMAIL Setting Bit value
  59. if ($bf->get(UserPrivacySettings::PRIVACY_EMAIL))
  60. {
  61.     echo '<br><font color="green">PRIVACY_EMAIL Setting is ON/TRUE</font><br>';
  62. }else{
  63.     echo '<br><font color="red">PRIVACY_EMAIL Setting is OFF/FALSE</font><br>';
  64. }
  65.  
  66. // The Bits value, this is the number that we will store in the users settings database or anywhere else, all the settings a user has on or off are determined from this number alone. this is the cool part and I have not seen anyone else use bit fields and stuff in PHP like my class here does, I like it.
  67. echo $bf->getValue();
  68.  
  69. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement