开发者

Extended PHP ArrayObject Does Not Work Properly

开发者 https://www.devze.com 2022-12-21 22:39 出处:网络
I\'m trying to extend the SPL ArrayObject but I\'ve hit a little snag.Using an unmodified ArrayObject, this code works:

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 tak开发者_如何转开发e to make my extended class work with multidimensional arrays?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号