11

I have a question regarding ArrayObject. I wanted to use array_slice in an ArrayObject class and I couldn't. Is there a way to do it, without needing to write an "slice" method to the class that implements ArrayObject?

2 Answers 2

6

You can always work on the array copy:

$array = $object->getArrayCopy();
// modify $array as needed, e.g. array_slice(....) 
$object = new ArrayObject($array);

There sometime in the past was the idea to make all functions that accept arrays (or probably many of them) to accept ArrayObject as well. But I dunno how far that has gone and if it's still followed. I think ArrayObject is more a behavioural thing than actually replacing the native array in PHP.

Related question: PHP Array and ArrayObject

Sign up to request clarification or add additional context in comments.

8 Comments

This is easy to implement, but it's bad on memory. If that's important, it will be worth it to just implement your own ArrayObject-like class where you have access to the private array data such that you can manipulate it directly.
I must admit I have no clue about ArrayObject internals.
I was looking to avoid the use of getArrayCopy() because of the size of the array (+400k items).
Just curious, is there a reason that blocks you from using just a standard array firsthand? And/or is extending ArrayObject an option for in your case?
it's a result from a database, the original class is an ArrayObject with some extra implementations (mostly iterators). extending this class is some messy business
|
0

Having a class that wraps php array functions is not that bad idea. Will make code much cleaner.

echo $myAry->slice(10, 5)->reverse()->join(", ");

Just like a normal language, you know.

1 Comment

that looks really cool @hakre. @stereofrog, how the data should be accessed inside the slice() method without duplicating data?

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.