簡體   English   中英

為什么實現ArrayAccess,Iterator和Countable的類不能與array_filter()一起使用?

[英]Why does a class that implements ArrayAccess, Iterator, and Countable not work with 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 ,或者首先從對象創建數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM