Skip to content

Instantly share code, notes, and snippets.

@BrainInBlack
Last active September 3, 2017 22:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BrainInBlack/869d243c4d649f0d68753491f92abeb0 to your computer and use it in GitHub Desktop.
Save BrainInBlack/869d243c4d649f0d68753491f92abeb0 to your computer and use it in GitHub Desktop.
Bitwise Flag Trait for PHP 7.x+
<?php
declare(strict_types=1);
/**
* Bitwise Flags Trait
* Trait that makes it easy to use Bitwise Flags in your classes.
* @version 7.0.2
* @author Daniel "BrainInBlack" Lieberwirth <braininblack@gmail.com>
* @author PHP Manual Contributer wbcart (http://php.net/manual/en/language.operators.bitwise.php#108679)
* @license DO WHAT EVER THE HECK YOU WANT
*/
trait BitwiseFlags {
/**
* Flag Container Variable.
* @var int
*/
protected $Flags = 0;
/**
* Checks if a Flag is set, i.e. if the Flag is true.
* @param int $flag Flag(s)
* @return bool <b>True:</b> If Flag(s) set<br>
* <b>False:</b> Otherwise
*/
protected function isFlagSet(int $flag) : bool {
return (($this->Flags & $flag) == $flag);
}
/**
* Sets Flag(s) to a specific value, i.e. true or false.
* @param int $flag Flag(s)
* @param bool $value Value
*/
protected function setFlag(int $flag, bool $value) {
$value ? $this->Flags |= $flag : $this->Flags &= ~$flag;
}
}
?>
Description&Usage:
See http://php.net/manual/en/language.operators.bitwise.php#108679
for a great example and description. I trust that you know how to use
Traits in your classes, otherwise ask the SearchEngine of your choice.
History:
v7.0.2 - Fixed setFlag false value case
v7.0.1 - First public release
DO WHAT EVER THE HECK YOU WANT
Comercial use: permitted
Private use: permitted
Modification: permitted
Credit: not required, but very welcome
This Programm/Snippet/Code is provided as is.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment