note 86370 deleted from language.operators.bitwise by danielc

From: Date: Mon, 13 Apr 2009 16:09:42 +0000
Subject: note 86370 deleted from language.operators.bitwise by danielc
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-153151@lists.php.net to get a copy of this message
Note Submitter: sublimino @ the mail of g dot com Reason: 1 ---- @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: <?php 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.

« previous php.notes (#153151) next »