首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么实现ArrayAccess、迭代器和Countable的类不能使用array_filter()?

为什么实现ArrayAccess、迭代器和Countable的类不能使用array_filter()?
EN

Stack Overflow用户
提问于 2010-08-23 04:12:32
回答 1查看 4.3K关注 0票数 7

我有以下类:

代码语言:javascript
复制
<?php

/*
* Abstract class that, when subclassed, allows an instance to be used as an array.
* Interfaces `Countable` and `Iterator` are necessary for functionality such as `foreach`
*/
abstract class AArray implements ArrayAccess, Iterator, Countable
{
    private $container = array();

    public function offsetSet($offset, $value) 
    {
        if (is_null($offset)) {
            $this->container[] = $value;
        } else {
            $this->container[$offset] = $value;
        }
    }

    public function offsetExists($offset) 
    {
        return isset($this->container[$offset]);
    }

    public function offsetUnset($offset) 
    {
        unset($this->container[$offset]);
    }

    public function offsetGet($offset) 
    {
        return isset($this->container[$offset]) ? $this->container[$offset] : null;
    }

    public function rewind() {
            reset($this->container);
    }

    public function current() {
            return current($this->container);
    }

    public function key() {
            return key($this->container);
    }

    public function next() {
            return next($this->container);
    }

    public function valid() {
            return $this->current() !== false;
    }   

    public function count() {
     return count($this->container);
    }

}

?>

然后,我有另一个子类AArray:

代码语言:javascript
复制
<?php

require_once 'AArray.inc';

class GalleryCollection extends AArray { }

?>

当我用数据填充GalleryCollection实例,然后尝试在array_filter()中使用它时,在第一个参数中,我得到了以下错误:

代码语言:javascript
复制
Warning: array_filter() [function.array-filter]: The first argument should be an array in
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-08-23 04:13:59

因为array_filter只适用于数组。

看看其他选项,比如FilterIterator,或者先从你的对象创建一个数组。

票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3543161

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档