Extended PHP ArrayObject Does Not Work Properly

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?

Answers


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.


Need Your Help

netbeans 6.9.1 + rails 3 + ruby 1.9.2p0 debugging

ruby-on-rails ruby debugging netbeans

I'm running OpenSuSE 11.3 and am having problems debugging rails3 application in NetBeans 6.9.1 (ruby 1.9.2p0, rails 3.0.3, rvm).

How can I find the nearest possible open place for pygame collision detection?

python collision-detection pygame

I have the collision detection down. Now, I need to find where to move the player so that he is not clipping any blocks. Once I have the collision detection, I want to move the player to the neares...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.