How can I parse a configuration value with PHP which is a number and a total of other numbers.
One example of this is:
1 -> Logging En开发者_JS百科abled
2 -> Error Reporting Enabled 4 -> E-Mail Reporting Enabled3 -> Logging + Error Enabled
5 -> Logging + E-Mail EnabledYou don't just have a sum -- you have yourself a set of flags, or a bit field, with each flag represented by one bit.
$logging = !!($cfgval & 1);
$errorReport = !!($cfgval & 2);
$emailReport = !!($cfgval & 4);
The "!!" just ensures that numbers that aren't 0 (ie: numbers with the specific bit set) end up as the same "true" value that the rest of PHP uses, so stuff like ($logging == true)
always works as expected. It's not required, but i highly recommend you convert the value to a boolean somehow; (bool)
would work as well, even if it is 3 times as many characters. :)
As long as you keep the numbers as powers of two (1, 2, 4, 8, 16, 32...), it's easy to extend this up to 31-32 different flags (integers are 32 bits in size, but the top bit is a sign bit which acts kinda funny if you don't know about "two's complement" math).
精彩评论