Given object $obj
, how do I set $obj->foo[4]->bar[2]->fee->fi->fo->fum
equal to "hello", and create the parent arrays and objects if they don't currently exist?
Given object $obj
, and string foo[4]->bar[2]->fee->fi->fo->fum
, is there any way to similarly do so?
Here it is a proposal, it works, not sure if it is the more elegant but works:
$obj = new stdClass();
$stringParams = "foo[4]->bar[2]->fee->fi->fo->fum";
$attributes = explode("->", $stringParams);
foreach($attributes as $attribute) {
$attributeBase = explode("[", $attribute);
if(count($attributeBase) > 1) {
$attributeIndex = (int)str_ireplace("]","", $attributeBase[1]);
$obj->$attributeBase[0] = [$attributeIndex => null];
} else {
$obj->{$attribute} = null;
}
}
var_dump($obj);
Pretty much stole Darren's idea, but added one @
character. Still don't like the idea of suppressing errors or warnings of any kind. Doesn't address the additional question how to access if the path is given as a string, but that wasn't the primary question.
<?php
$obj = new stdClass();
@$obj->foo[4]->bar[2]->fee->fi->fo->fum = 'hello';
echo($obj->foo[4]->bar[2]->fee->fi->fo->fum);