gpt4 book ai didi

php - 为什么实现 ArrayAccess、Iterator 和 Countable 的类不能使用 array_filter()?

转载 作者:可可西里 更新时间:2023-11-01 13:16:57 25 4
gpt4 key购买 nike

我有以下类(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 只适用于数组。

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

关于php - 为什么实现 ArrayAccess、Iterator 和 Countable 的类不能使用 array_filter()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3543161/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com