17

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

1 Answer 1

15

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 …
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thought so, but just in case asked. Ty
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 yes, because these functions expect arrays for input. A class implementing ArrayAccess is not the same type as an array.
Think of specifying "array" type as a test of "instance of array" - and ArrayAccess is not an "instance" of array, obviously... for now... it would be awesome if you could replace that, since you could leverage so many things during the input, e.g. stream output when using exec() etc...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.