Skip to content

Instantly share code, notes, and snippets.

@diloabininyeri
Created December 16, 2023 05:08
Show Gist options
  • Save diloabininyeri/9acd3995cde13d2964055e78cce471ee to your computer and use it in GitHub Desktop.
Save diloabininyeri/9acd3995cde13d2964055e78cce471ee to your computer and use it in GitHub Desktop.
Bitwise operations permission system example in PHP
class Permission
{
private const int READ = 10;
private const int WRITE = 20;
private const int DELETE = 40;
private int $permission = 0;
public function giveRead(): void
{
$this->permission |= self::READ;
}
public function giveWrite(): void
{
$this->permission |= self::WRITE;
}
public function giveDelete(): void
{
$this->permission |= self::DELETE;
}
public function toInteger(): int
{
return $this->permission;
}
/**
* @noinspection PhpUnused
* @return void
*/
public function removeWrite(): void
{
$this->permission &= ~self::WRITE;
}
/**
* @noinspection PhpUnused
* @return bool
*/
public function hasWrite(): bool
{
return ($this->permission & self::WRITE) === self::WRITE;
}
public function hasRead(): bool
{
return ($this->permission & self::READ) === self::READ;
}
public function toBinary(): string
{
return sprintf('%b', $this->toInteger());
}
public function removeDelete(): void
{
$this->permission &= ~self::DELETE;
}
}
$permission = new Permission();
$permission->giveDelete();
$permission->giveWrite();
echo $permission->hasRead();
$permission->removeWrite();
$permission->toBinary();
$permission->toInteger();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment