Which SPL interface I must implement to be able to use usort() function on an object?

StackOverflow https://stackoverflow.com/questions/15136568

  •  16-03-2022
  •  | 
  •  

Question

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().

Was it helpful?

Solution 2

Not that I know of. No interface will make your object be also an array and that's what you need to pass to usort(). However you can encapsulate this behaviour in your class by adding usort() method to your class.

class CollectionEntity implements Countable, IteratorAggregate, ArrayAccess {

  private $data = array();

  /* other methods omitted for simplicity */

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


}

OTHER TIPS

I really think the only class you should extend is ArrayIterator because it already implements

ArrayIterator implements Iterator , Traversable , ArrayAccess , SeekableIterator , Countable , Serializable

Also also it supports

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

And so many other methods

So you class is as simple as

class CollectionEntity extends ArrayIterator {
}

Then

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

There is no such interface, array functions can only work on native arrays. However, you can convert Traversables such as IteratorAggregate to arrays with iterator_to_array

By the way, here is an explanation why especially ArrayAccess does not help: PHP: how can I sort and filter an "array", that is an Object, implementing ArrayAccess?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top