sokil / php-bitmap
使用位运算进行位图表示
2.0
2021-01-19 12:35 UTC
Requires
- php: >=7.1
Requires (Dev)
- phpunit/phpunit: >=7.5.20
This package is auto-updated.
Last update: 2024-09-17 17:46:14 UTC
README
位图,也称为位数组,是一种紧凑地存储整数值的数据结构。有关更多信息,请参阅 http://en.wikipedia.org/wiki/Bit_array。
当需要以紧凑的方式表示值的组合并进行简单操作时非常有用。一个字节可以表示八个独立值。
安装
composer require sokil/php-bitmap
用法
让我们看看一个例子。PHP中的错误表示为常量
E_ERROR = 1 (0);
E_WARNING = 2 (1);
E_PARSE = 4 (2);
E_NOTICE = 8 (3);
E_CORE_ERROR = 16 (4);
E_CORE_WARNING = 32 (5);
E_COMPILE_ERROR = 64 (6);
E_COMPILE_WARNING = 128 (7);
E_USER_ERROR = 256 (8);
E_USER_WARNING = 512 (9);
E_USER_NOTICE = 1024 (10);
E_STRICT = 2048 (11);
E_RECOVERABLE_ERROR = 4096 (12);
E_DEPRECATED = 8192 (13);
E_USER_DEPRECATED = 16384 (14);
E_ALL = 32767 (15);
每个错误级别代表逻辑 "1",所有这些值的组合只能用两个字节表示。E_ERROR 表示字节的第一个位,E_WARNING 表示第二个位,等等。
E_WARNING 和 E_NOTICE 在二进制系统中为 "1010",在十进制系统中为 10。
表示 PHP 错误位图的类
class PhpError extends \Sokil\Bitmap { /** * Show errors * Set first bit, which represents E_ERROR, to "1" */ public function showErrors() { $this->setBit(0); return $this; } /** * Hide errors * Set first bit, which represents E_ERROR, to "0" */ public function hideErrors() { $this->unsetBit(0); return $this; } /** * Check if errors shown * Check if first bit set to 1 */ public function isErrorsShown() { return $this->isBitSet(0); } /** * Show warnings * Set second bit, which represents E_WARNING, to "1" */ public function showWarnings() { $this->setBit(1); return $this; } /** * Hide warnings * Set second bit, which represents E_WARNING, to "0" */ public function hideWarnings() { $this->unsetBit(1); return $this; } /** * Check if warnings shown * Check if second bit set to 1 */ public function isWarningsShown() { return $this->isBitSet(1); } }
现在我们可以轻松地操作错误
// load current error levels $error = new PhpError(error_reporting()); // enable errors and warnings $error->showErrors()->showWarnings(); // set error reporting error_reporting($error->toInt()); // check if warnings shown var_dump($error->isWarningsShown()); // value may be set by mask // E_USER_ERROR | E_USER_WARNING is 256 + 512; $error->setBitsByMask(E_USER_ERROR | E_USER_WARNING);