16

Is there any way to use array_merge(), array_pop(), .. functions to work with ArrayAccess?

Since now i've tried Iterate interface and __set_state() magic method with no success.

Error that is given: array_replace_recursive() [<a href='function.array-replace-recursive'>function.array-replace-recursive</a>]: Argument #1 is not an array.

Just fo a record, gettype() returns object and is_array() returns false and i'm usin php version 5.3.8

Kristian
  • 3,283
  • 3
  • 28
  • 52

1 Answers1

14

Unfortunately, no. They only work with the native array type. You have to add those as methods to your object's public API and implement them there, e.g. something like this:

class YourClass implements ArrayAccess, Countable
{
    public function pop()
    {
        $lastOffset = $this->count() - 1;
        $lastElement = $this->offsetGet($lastOffset);
        $this->offsetUnset($lastOffset);

        return $lastElement;
    }

    public function mergeArray(array $array) {
        // implement the logic you want
    }

    // other code …
}
Gordon
  • 312,688
  • 75
  • 539
  • 559
  • Thought so, but just in case asked. Ty – Kristian Jan 09 '12 at 11:58
  • I don't understand this answer - are you saying that I would need to implement `array_merge` and other native array functions as methods of my `ArrayAccess`-implementing class? – alexw Mar 31 '16 at 21:11
  • @alexw yes, because these functions expect arrays for input. A class implementing ArrayAccess is not the same type as an array. – Gordon Apr 01 '16 at 05:11