为什么实现ArrayAccess,Iterator和Countable的类不能与array_filter()一起使用?

时间:2010-08-22 20:12:32

标签: php custom-controls array-filter

我有以下课程:

<?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的类:

<?php

require_once 'AArray.inc';

class GalleryCollection extends AArray { }

?>

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

Warning: array_filter() [function.array-filter]: The first argument should be an array in

谢谢!

1 个答案:

答案 0 :(得分:8)

因为array_filter仅适用于数组。

查看其他选项,例如FilterIterator,或先从对象创建数组。