2

I have a class that represents a collection entity : it has only one attribute, an array. This class implements \Countable, \IteratorAggregate, and the most important for this question, \ArrayAccess.

But when using :

        usort($collectionData, function($a, $b) {
            return ($a->getPosition() > $b->getPosition());
        });

I get the following catchable exception :

Warning: usort() expects parameter 1 to be array, object given in /home/alain/workspace/(...)n.php line 1057 (500 Internal Server Error)

I can trick using an intermediate variable :

        $data = $collectionData->getData();
        usort($data, function($a, $b) {
            return ($a->getPosition() > $b->getPosition());
        });
        $collectionData->setData($data);

But wanted to know if there is an SPL interface that can pass through the array parameter type expectation of usort().

4

3 回答 3

2

我真的认为你应该扩展的唯一类是 ArrayIterator因为它已经实现了

ArrayIterator 实现了 Iterator , Traversable , ArrayAccess , SeekableIterator , Countable , Serializable

它还支持

 public void uasort ( string $cmp_function )
 public void uksort ( string $cmp_function )

还有很多其他方法

所以你的课很简单

class CollectionEntity extends ArrayIterator {
}

然后

$collectionData->uasort(function ($a, $b) {
    return ($a->getPosition() > $b->getPosition());
});
于 2013-02-28T13:39:37.683 回答
1

从来没听说过。没有接口会使你的对象也是一个array,这就是你需要传递给usort(). usort()但是,您可以通过向您的类添加方法来将此行为封装在您的类中。

class CollectionEntity implements Countable, IteratorAggregate, ArrayAccess {

  private $data = array();

  /* other methods omitted for simplicity */

  public function usort(Closure $callback) {
    usort($this->data,$callback);
  }


}
于 2013-02-28T13:23:42.343 回答
-2

没有这样的接口,数组函数只能作用于原生数组。但是,您可以将 Traversables 转换为IteratorAggregate数组,例如iterator_to_array

顺便说一句,这里有一个解释为什么特别ArrayAccess没有帮助:PHP:我如何排序和过滤一个“数组”,即一个对象,实现 ArrayAccess?

于 2013-02-28T13:27:36.063 回答