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
array_filter()
中使用该扩展的实例吗? - Mike Moorearray
不是一个类(在 PHP 5.3 中)。 - VolkerKarray_filter
只能用于 PHP 中array
类型的东西,而不是object
,因为任何类实例都将不起作用。如果你想从迭代器中获取一个数组,请使用iterator_to_array()
。如 Artefacto 所说,要过滤迭代器中的值,应该使用FilterIterator
。 - salatheiterator_to_array()
函数。有了@Artefacto的建议,从对象创建数组,我能够轻松地使用iterator_to_array()
实现它。 - Mike Moore