note 86370 added to language.operators.bitwise
| From: | sublimino at themailofgdotcom | Date: | Wed, 15 Oct 2008 12:02:42 +0000 |
| Subject: | note 86370 added to language.operators.bitwise | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-145375@lists.php.net to get a copy of this message | ||
@wbcarts at juno dot com
This code is unlikely to work as expected as you are not evaluating the whole expression, and your
test cases are not equivalent to a bitmask's operation.
This will produce unexpected results:
public function isNotForSale(){
return ($this->flags & self::$NFS > 0);
}
This will work correctly when using brackets:
return (($this->flags & self::$NFS) > 0);
Or more simply remove the greater than and evaluate the expression as true or false:
class Artwork
{
protected static $HIDDEN = 1; // bitmask for 1st bit (0x1) - do not show this item
protected static $NFS = 2; // bitmask for 2nd bit (0x2) - not for sale
protected static $SOLD = 4; // bitmask for 3rd bit (0x4) - item is already sold
protected $flags = 0; // the property we're interested in...
// simple setter function for any declared static variable
public function setFlag( $flag, $state )
{
$this->flags = ($state ? ($this->flags | self::$$flag) : ($this->flags &
~self::$$flag));
}
// returns the state of the flag
public function hasFlag( $flag )
{
return( $this->flags & self::$$flag );
}
// outputs an integer representation of the bitmask
public function __toString(){
return "Artwork [flags=$this->flags]";
}
}
$art = new Artwork();
$art->setFlag( 'HIDDEN', true );
$art->setFlag( 'NFS', false );
$art->setFlag( 'SOLD', true );
foreach( array( 'HIDDEN', 'NFS', 'SOLD' ) as $v ) {
if( $art->hasFlag( $v ) ) {
echo "<br/>Set: $v";
}
}
echo "$art<br/>";
While using PHP's magic setter method may seem more elegant, the enforcement of static types in
the above snippet results in a fatal error if an undeclared static variable is referenced, which is
more useful in this situation as it prevents typos etc.
Fatal error: Access to undeclared static property: Artwork::$UNSET_STATIC_VAR in (file)
HTH.
----
Server IP: 92.48.74.199
Probable Submitter: 212.248.206.73
----
Manual Page -- http://www.php.net/manual/en/language.operators.bitwise.php
Edit -- https://master.php.net/note/edit/86370
Del: integrated -- https://master.php.net/note/delete/86370/integrated
Del: useless -- https://master.php.net/note/delete/86370/useless
Del: bad code -- https://master.php.net/note/delete/86370/bad+code
Del: spam -- https://master.php.net/note/delete/86370/spam
Del: non-english -- https://master.php.net/note/delete/86370/non-english
Del: in docs -- https://master.php.net/note/delete/86370/in+docs
Del: other reasons-- https://master.php.net/note/delete/86370
Reject -- https://master.php.net/note/reject/86370
Search -- https://master.php.net/manage/user-notes.php