开发者

Using usort() with an object that implements ArrayIterator

I have this class:

class ResultSet 
    implements ArrayAccess, Countable, Iterator {
     /// Rest of implementation ...
}

I'm running into a problem using usort() and passing my object as the first parameter. usort() expects an array instead of an object, but given my implementation of the ArrayAccess开发者_StackOverflow社区 interface I don't know what else it could be needing.

The exact error returned by php is: Warning: usort() expects parameter 1 to be array, object given.


How would usort know how you've implemented ArrayAccess? There is no defined place where the values are kept -- that flexibility is the whole point of the interface.

If you are storing the elements in an array that is a private member of the object, you could proxy the usort operation. For example:

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


If memory serves, there's a big warning sign on the ArrayAccess page, or in one of the comments on it (probably the latter, in fact). It basically says something in the order of: the interface is somewhat useless, because PHP's array functions don't recognize any of its members as arrays.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜