views:

194

answers:

2

I'm trying to extend the SPL ArrayObject but I've hit a little snag. Using an unmodified ArrayObject, this code works:

$a = new ArrayObject();
$a[1][2] = 'abc';
print_r($a);

yielding this output:

ArrayObject Object
(
    [storage:ArrayObject:private] => Array
        (
            [1] => Array
                (
                    [2] => abc
                )

        )
)

However if I extend ArrayObject and overload the offsetGet method

class ExtendedArray extends ArrayObject {
    function offsetGet($i) {
        return parent::offsetGet($i);
    }
}

$a = new ExtendedArray();
$a[1][2] = 'abc';
print_r($a);

it then fails like this:

ExtendedArray Object
(
    [storage:ArrayObject:private] => Array
        (
        )

)

What does it take to make my extended class work with multidimensional arrays?

A: 

Here is the possible solution.

Sarfraz
+1  A: 

For me, the snippet #1 is rather broken, not the #2. You're accessing an element that does not exists, and the code #2 gives you exactly what one would expect: a warning. The reason why #1 kinda "works" is a quirk, or two quirks of php. First, when you apply []= operator on null, this null is "magically" turned into an array - without single word of warning from interpreter.

$a = null;
$a[1] = 'foo'; // "works"
print_r($a); 

Second, this (intentionally or not) does not apply to nulls returned from __get or offsetGet.

class foo {
    function __get($s) { return null; }
}

$a = new foo;
$a->x[1] = 'foo'; // error
print_r($a);  

the error message says "Indirect modification of overloaded property", and, whatever that means, it's a Good Thing - you're not allowed to modify the null value in any way.

stereofrog