简体   繁体   English

FilterIterator位掩码(或位域)

[英]FilterIterator bitmask (or bitfield)

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. 我想创建一个DirectoryFilterIterator,它接受要过滤的内容的标志。 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 like to be able to distinguish between those two also. 因为DOT也被认为是DIR所以我也希望能够区分这两者。 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 . 换句话说,这应该过滤掉DIR除非它是DOT But I'm totally stuck on how to get the filtering to work (in the accept method): 但是我完全迷住了如何使过滤工作(在accept方法中):

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. 使用位掩码时,需要将其值设置为2的幂。 If you set DIR to 3, it means it's synonymous to both DIR_NO_DOT and DOT combined. 如果将DIR设置为3,则意味着它是DIR_NO_DOT和DOT组合的同义词。

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 . 现在,您可以使用表达式DIR & !DOT检查项目是否为DIR而不是DIR & !DOT

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM