note 38646 deleted from language.operators.bitwise by nlopess

From: Date: Thu, 01 Jan 2004 16:22:51 +0000
Subject: note 38646 deleted from language.operators.bitwise by nlopess
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-62745@lists.php.net to get a copy of this message
Note Submitter: ---- You probably already know this, espicially all you C programmers out there, but bitwise operators provide a handy way to pass a lot of boolean flags to a function without having to specify a long list of boolean arguments or an array of booleans. You can just use a single integer instead. For example, if you have a function that needs 5 flags you might declare it as: <?php function dosomething ($arg1,$arg2,$arg3,$arg4,$arg5) { if ($arg1) echo ('Flag 1 set<br />'); if ($arg2) echo ('Flag 2 set<br />'); if ($arg3) echo ('Flag 3 set<br />'); if ($arg4) echo ('Flag 4 set<br />'); if ($arg5) echo ('Flag 5 set<br />'); echo ('<hr />'); } dosomething (true,true,true,true,true); ?> you could try the following example: <?php define ("FLAG_1",1); define ("FLAG_2",2); define ("FLAG_3",4); define ("FLAG_4",8); define ("FLAG_5",16); function dosomething_bitwise ($flags) { if ($flags & FLAG_1) echo ('Flag 1 set<br />'); if ($flags & FLAG_2) echo ('Flag 2 set<br />'); if ($flags & FLAG_3) echo ('Flag 3 set<br />'); if ($flags & FLAG_4) echo ('Flag 4 set<br />'); if ($flags & FLAG_5) echo ('Flag 5 set<br />'); echo ('<hr />'); } dosomething_bitwise (FLAG_1); dosomething_bitwise (FLAG_2); dosomething_bitwise (FLAG_3); dosomething_bitwise (FLAG_4); dosomething_bitwise (FLAG_5); dosomething_bitwise (FLAG_1|FLAG_2); dosomething_bitwise (FLAG_1|FLAG_2|FLAG_3); dosomething_bitwise (FLAG_1|FLAG_2|FLAG_3|FLAG_4); dosomething_bitwise (FLAG_1|FLAG_2|FLAG_3|FLAG_4|FLAG_5); dosomething_bitwise (FLAG_2|FLAG_3|FLAG_4|FLAG_5); dosomething_bitwise (FLAG_3|FLAG_4|FLAG_5); dosomething_bitwise (FLAG_4|FLAG_5); dosomething_bitwise (FLAG_5); ?> Flags are or'd together when calling the function to specify what bits to set. The bits are tested in the function by anding them. The second method requires a little extra setting up with the defines for the flags, but in use the advantages are obvious. In the first example you had to specify all the flags explicitly when calling the function or you'll get errors. In the bitwise version you only need to specify the flags you're actually going to set. Additionally, as long as you pick meaningful names for your flags, the bitwise version will be more readable and therefore more easy to maintain. Also adding to maintainability is the fact you can add new flags (up to the bit size of the integer type) without having to change any pre-existing code that calls the function. For example I could create a FLAG_SIX with a value of 32 and add code to test for it in the function without having to change my calling lines, as long as they don't need to use the feature that FLAG_6 activates.

« previous php.notes (#62745) next »