Bitwise is useful for things in PHP just like anything else.
How about a value that can have multiple states turned on at the same time?
<?php
// since we're setting constant values in base10 we must progressively double
// them since bitwise operations work in base2. you'll see why when we output
// these as binary values below.
const STATE_FOO = 1;
const STATE_BAR = 2;
const STATE_FEZ = 4;
const STATE_BAZ = 8;
// show base2 values of the above constants
echo sprintf("STATE_FOO's base2 value is %08d
", decbin(STATE_FOO));
echo sprintf("STATE_BAR's base2 value is %08d
", decbin(STATE_BAR));
echo sprintf("STATE_FEZ's base2 value is %08d
", decbin(STATE_FEZ));
echo sprintf("STATE_BAZ's base2 value is %08d
", decbin(STATE_BAZ));
// set state to FOO and FEZ
$state = STATE_FOO | STATE_FEZ;
echo sprintf("base10 value of $state is %s
", $state);
echo sprintf("base2 value of $state is %08d
", decbin($state));
echo sprintf("Does $state include FOO state? %s
", (bool)($state & STATE_FOO));
echo sprintf("Does $state include BAR state? %s
", (bool)($state & STATE_BAR));
echo sprintf("Does $state include FEZ state? %s
", (bool)($state & STATE_FEZ));
echo sprintf("Does $state include BAZ state? %s
", (bool)($state & STATE_BAZ));
echo sprintf("Is state equivalent to FOO and FEZ states? %s
", ($state == (STATE_FOO | STATE_FEZ)));
Output:
STATE_FOO's base2 value is 00000001
STATE_BAR's base2 value is 00000010
STATE_FEZ's base2 value is 00000100
STATE_BAZ's base2 value is 00001000
base10 value of $state is 5
base2 value of $state is 00000101
Does $state include FOO state? 1
Does $state include BAR state?
Does $state include FEZ state? 1
Does $state include BAZ state?
Is state equivalent to FOO and FEZ states? 1
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…