Class flags with bitwise operators

bitwise operatorsThere is a group of  PHP features that most of developers don’t usually use: bitwise operators.

These operators are widely used in the C language to make low-level applications (device drivers, protocols etc..). They are very useful when used in OOP developing as a flags for options in functions, classes and general settings.

Brief overview

There are 6 bitwise operators in PHP: And (&), Or (|), Xor (^), not (~), shift left(<<) and right(>>). I won’t to explain here their semantic as it’s not the purpose of this post, read the official documentation [link] if you don’t know how the bitwise operator work.

Use of as a flags : error_reporting

When an array of N binary (on/off) options is needed, the idea is using bitwise operators to store all the options within one integer value, that is a string (or array or word) of bits.
Normally, N constants are set to the values 1,2,4,8, … ,2^(N-1) so that with bitwise operator it’s possible to combine them and obtain any possible configuration of the string.
Continue reading