一个实现了ArrayAccess、Iterator和Countable接口的类为什么不能与array_filter()一起使用?

7

I have the following class:

<?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个回答

10

由于 array_filter 只能用于数组。

可以考虑其他选项,比如 FilterIterator,或者先从对象创建一个数组。


你知道是否可能扩展Array类并在array_filter()中使用该扩展的实例吗? - Mike Moore
3
不可能实现,而且array不是一个类(在 PHP 5.3 中)。 - VolkerK
6
array_filter 只能用于 PHP 中 array 类型的东西,而不是 object,因为任何类实例都将不起作用。如果你想从迭代器中获取一个数组,请使用 iterator_to_array()。如 Artefacto 所说,要过滤迭代器中的值,应该使用 FilterIterator - salathe
谢谢。我不确定它是否是一个数组。 - Mike Moore
3
@VolkerK - 呜,我觉得自己很蠢。@salathe - 非常感谢您分享iterator_to_array()函数。有了@Artefacto的建议,从对象创建数组,我能够轻松地使用iterator_to_array()实现它。 - Mike Moore

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接