Access to multidimensional arrays through ArrayAccess

Let's say I have the following code:

<?php

class test implements ArrayAccess {
    var $var;

    function __construct()
    {
        $this->var = array(
            'a' => array('b' => 'c'),
            'd' => array('e' => 'f'),
            'g' => array('h' => 'i')
        );
    }

    function offsetExists($offset)
    {
        return isset($this->var);
    }

    function offsetGet($offset)
    {
        return isset($this->var[$offset]) ? $this->var[$offset] : null;
    }

    function offsetSet($offset, $value)
    {
        if (is_null($offset)) {
            $this->var[] = $value;
        } else {
            $this->var[$offset] = $value;
        }
    }

    function offsetUnset($offset)
    {
        unset($this->var[$offset]);
    }
}

$test = new test();
$test['a']['b'] = 'zzz';

print_r($test->var);

What I would like to do is show the following:

Array
(
    [a] => Array
        (
            [b] => zzz
        )

    [d] => Array
        (
            [e] => f
        )

    [g] => Array
        (
            [h] => i
        )

)

What it actually displays is more like this:

Array
(
    [a] => Array
        (
            [b] => c
        )

    [d] => Array
        (
            [e] => f
        )

    [g] => Array
        (
            [h] => i
        )

)

t. $test['a']['b']does not change.

Any idea how I can make it mutable using this syntax? I could assign to a $test['a']variable and then do $temp['b'] = 'zzz';and then do $test['a'] = $temp;, but idk - this seems excessive.

+4
source share
2 answers

The problem is that it offsetGetreturns an array by value, i.e. copy of internal meaning. $test['a']['b'] = 'zzz'works with this copy returned $test['a'].

offsetGet :

    function &offsetGet($offset)
    {
        $null = null;
        if (isset($this->var[$offset])) {
            return $this->var[$offset];
        }
        return $null;
    }

, , return , .

:

https://3v4l.org/4jGMN

5.4.7 - 7.0.0rc2, hhvm-3.6.1 - 3.9.0

Array
(
    [a] => Array
        (
            [b] => zzz
        )

    [d] => Array
        (
            [e] => f
        )

    [g] => Array
        (
            [h] => i
        )

)

Update

:

function &offsetGet($offset)
{
    return $this->v[$offset];
}

, , . :

$test['new']['nested'] = 'xxx';

: https://3v4l.org/OSvuA

+1

.

$test = new test();
$data = $test -> var;
$data['a']['b']= 'ssss';

print_r($data) ;

.

0

Source: https://habr.com/ru/post/1606533/


All Articles