简体   繁体   中英

PHP Integer Configuration (e.g. 1=apache,2=php,3=apache+php)

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 Enabled
2 -> Error Reporting Enabled
4 -> E-Mail Reporting Enabled

3 -> Logging + Error Enabled
5 -> Logging + E-Mail Enabled

You 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM