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

Mik*_*ore 7 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);
    }

}

?>
Run Code Online (Sandbox Code Playgroud)

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

<?php

require_once 'AArray.inc';

class GalleryCollection extends AArray { }

?>
Run Code Online (Sandbox Code Playgroud)

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

Warning: array_filter() [function.array-filter]: The first argument should be an array in
Run Code Online (Sandbox Code Playgroud)

谢谢!

Art*_*cto 9

因为array_filter只适用于数组.

查看其他选项,FilterIterator或者首先从对象创建一个数组.

  • @letseatfood,`array_filter`只适用于PHP中`array`类型的东西...而不是任何类实例的`object`.如果要从迭代器中获取数组,请使用[`iterator_to_array()`](http://php.net/iterator_to_array).要过滤迭代器中的值,正如Artefacto所说,你应该使用`FilterIterator`. (5认同)
  • 这是不可能的,`array`不是一个类(php 5.3). (3认同)
  • @VolkerK - 呃我觉得很傻.@salathe - 非常感谢您分享`iterator_to_array()`函数.随着@Artefacto建议从对象创建数组,我可以使用`iterator_to_array()`轻松完成. (2认同)