一个php操作状态位状态的类

平时经常有通过二进制位来存储多个开关位,实现一个字段存多个开关的功能。
每次操作位,难免容易出错,遂写了一个类简化操作,闲话少说上代码和使用方法。
BitState类:

<?php
class BitState {
    private $maps = [];
    private $state = 0;
    public function __construct($state = 0,$maps){
        $this->state = $state;
        $this->maps = $maps;
    }
    public function setOn($k) {
        $bit = $this->stateBit($k);
        $this->state = $this->state|$bit;
        return $this->state;
    }
    public function setOff($k) {
        $bit = $this->stateBit($k);
        $this->state =  $this->state&(~$bit);
        return $this->state;
    }
    public function check($k) {
        $bit = $this->stateBit($k);
        if (($this->state & $bit) == $bit) {
            return 1;
        }
        return 0;
    }
    public function __toString(){
        return strval($this->state);
    }

    public function getState() {
        return $this->state;
    }
    public function getBinState() {
        return decbin($this->state)
    }
    private function stateBit($k) {
        if (isset($this->maps[$k])) {
            return $this->maps[$k];
        }
        return null;
    }
}

用法:
//初始化状态
$maps = [
'apple' => 1<<0,
'banana' => 1<<1,
'peach' => 1<<2,
];
//demo1
//创建一个状态值(初始为0)
$state = new BitState(0,$maps);
//设置这个状态值apple 位置 1
$state->setOn('apple');
//设置这个状态值peach 位置 1
$state->setOn('peach');
//输出这个值(10进制)
echo $state->getState(); //结果为 5
//或
echo $state; //结果为 5
//输出这个值二进制位形式(101)
echo $state->getBinState()

//demo2
//创建一个基于已有状态的状态位 (初始化4)
$state = new BitState(4,$maps); // 即初始化为 010
$state->setOn("apple");
$state->setOff("banana");
echo $state; // 输出1 即 001

仅有 1 条评论
  1. Austot

    Viagra Bestellen Per Nachnahme Keflex Decrease Milk Can I Purchase Elocon 5g achat de viagra pfizer en roubaix Buy Amoxicillin Liquid No Prescription Levitra 10 Mg Bayer Precio

    Austot 回复
发表新评论