What good are ArrayObjects?
Ever since I had my first encounter with the SPL, it took me a while to understand the actual usefulness of the ArrayObject. Its use isn’t obvious, because it only reveals itself if you want to follow a strict discipline of class encapsulation. Otherwise it doesn’t offer any advantage over the standard PHP array.
A lot of the confusion comes from the lack of documentation. An ArrayObject, the documentation says, is “an array wrapper”, that “allows to recursively iterate over Arrays and public Object properties”. This isn’t very useful, and it doesn’t explain at all what is the ArrayObject actually good for. Iteration over arrays and objects has been long supported simply with the foreach construct:
$arr = array( 'a', 'b', 'c' ); $arr[0] = 'A'; $arr[] = 'd'; echo count( $arr ); foreach( $arr as $letter ) echo $letter;
And this is how you’d do it with an ArrayObject:
$arrObject = new ArrayObject( array( 'a', 'b', 'c' ) ); $arrObject[0] = 'A'; $arrObject[] = 'd'; echo count( $arrObject ); foreach( $arrObject as $letter ) echo $letter;
