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

问题描述:

我有以下类:为什么实现ArrayAccess,Iterator和Countable的类不能与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 

谢谢!

因为array_filter只适用于数组。

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

+0

是否知道是否可以扩展Array类并在'array_filter()'中使用该扩展的实例? – 2010-08-22 20:16:38

+3

这不可能,'array'不是一个类(php 5.3)。 – VolkerK 2010-08-22 20:20:53

+5

@letseatfood,'array_filter'只适用于PHP中'数组'类型的东西,而不是任何类实例的'object'。如果你想从一个迭代器中取出一个数组,使用['iterator_to_array()'](http://php.net/iterator_to_array)。按照Artefacto的说法,要过滤迭代器中的值,你应该使用'FilterIterator'。 – salathe 2010-08-22 20:21:06