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
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
8 Comments
Matthew
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.
hakre
I must admit I have no clue about ArrayObject internals.
pocesar
I was looking to avoid the use of getArrayCopy() because of the size of the array (+400k items).
hakre
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?
pocesar
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
|
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
pocesar
that looks really cool @hakre. @stereofrog, how the data should be accessed inside the slice() method without duplicating data?