Extending ArrayObject in PHP properly?

前端 未结 3 1132
傲寒
傲寒 2021-02-09 08:02

Problem: I am trying to extend PHP\'s ArrayObject as shown below. Unfortunately I can\'t get it to work properly when setting multi-dimensional obj

3条回答
  •  不要未来只要你来
    2021-02-09 08:26

    Copied pasted your code and it works fine on my PHP test box (running PHP 5.3.6). It does mention the Strict Standards warning, but it still works as expected. Here's the output from print_r:

    Config Object
    (
        [storage:ArrayObject:private] => Array
            (
                [lvl1_0] => 1
                [lvl1_1] => stdClass Object
                    (
                        [lvl2] => 1
                    )
    
            )
    
    )
    

    It is worth noting that on the PHP docs there is a comment with guidance related to what you're trying to do:

    sfinktah at php dot spamtrak dot org 17-Apr-2011 07:27
    If you plan to derive your own class from ArrayObject, and wish to maintain complete ArrayObject functionality (such as being able to cast to an array), it is necessary to use ArrayObject's own private property "storage".

    Detailed explanation is linked above but, in addition to offsetSet which you have and offsetGet which xdazz mentions, you also must implement offsetExists and offsetUnset. This shouldn't have anything to do with your current error but it is something you should be mindful of.

    Update: xdazz' second-half has the answer to your problem. If you access your Config object as an array, it works without any errors:

    $config = new Config;
    $config[ 'lvl1_0' ] = true;
    $config[ 'lvl1_1' ][ 'lvl2' ] = true;
    

    Can you do that or are you restricted to the Object syntax for some reason?

提交回复
热议问题