Search code examples
phpstdclass

how to refrence a nested class value by array value


I think the best way to explain my question is to give an example. Say I have the following object.

$data=new stdClass;
$data->test=new stdClass;
$data->test->test2=6;
$data->s=array('b',6,7);

I want to know how I can read or change any value in the object given the key value as an array.

I know the below won't work:

function doSomething($inputArray1,$inputArray2) {
    $data[  $inputArray1   ]; //6
    $data[  $inputArray2   ]=4; //was array('b',6,7);
}

//someone else provided
doSomething( array('test','test2')  , array('s')  );

Changed to make clear that I do not know the values of the array personally so using $data->test->test2; to get the 6 like I normally would won't work. Also do not know the array length.


Solution

  • Figured it out:

    $parts=array('test','test2');
    
    
    $ref=&$data;
    foreach($parts as $part) {
        if (is_array($ref)) {
            $ref=&$ref[$part]; //refrence next level if array
        } else {
            $ref=&$ref->$part; //refrence next level if object
        }
    }
    echo $ref; //show value refrenced by array
    $ref=4; //change value refrenced by array(surprised this works instead of making $ref=4 and breaking the refrence)
    unset($ref); //get rid of refrence to prevent accidental setting.  Thanks @mpyw