I'm struggling with bitmasks (or is it bitfields?). I'm not sure how to do it anymore.
I want to create a DirectoryFilterIterator that accepts flags of what to filter. I thought I'd use these bits for that:
const DIR_NO_DOT = 1;
const DOT = 2;
const DIR = 3;
const FILE = 4;
Because a DOT
is also considered a DIR
I'd 开发者_如何学Pythonlike to be able to distinguish between those two also. If I'm correct I thought something like that should be possible like this:
DirectoryFilterIterator::DIR & ~DirectoryFilterIterator::DOT
In other words, this should filter out DIR
unless it's a DOT
. But I'm totally stuck on how to get the filtering to work (in the accept
method):
class DirectoryFilterIterator
extends FilterIterator
{
const DIR_NO_DOT = 1;
const DOT = 2;
const DIR = 3;
const FILE = 4;
protected $_filter;
public function __construct( DirectoryIterator $iterator, $filter = self::DIR )
{
parent::__construct( $iterator );
$this->_filter = $filter;
}
public function accept()
{
$item = $this->getInnerIterator()->current();
return (
!( ( $this->_filter & self::DOT ) == self::DOT && $item->isDot() ) &&
!( ( $this->_filter & self::DIR ) == self::DIR && $item->isDir() ) &&
!( ( $this->_filter & self::FILE ) == self::FILE && $item->isFile() )
);
}
}
...especially because of all the negating I have going on, I'm kind of lost. How can I get this to work properly?
When using bitmasks you need to set their values to powers of two. If you set DIR to 3, it means it's synonymous to both DIR_NO_DOT and DOT combined.
Try setting their values to something like this:
const DOT = 1;
const DIR = 2;
const FILE = 4;
Now you can check if an item is a DIR but not a DOT with the expression DIR & !DOT
.
精彩评论