在父属性最初可能不存在的位置设置PHP对象属性


Setting a PHP object property where the parent property may not initially exist

给定对象$obj,如何将$obj->foo[4]->bar[2]->fee->fi->fo->fum设置为"hello",并在当前不存在父数组和对象的情况下创建它们?

给定对象$obj和字符串foo[4]->bar[2]->fee->fi->fo->fum,有没有类似的方法?

这是一个建议,它有效,不确定它是否更优雅但有效:

$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);

几乎窃取了Darren的想法,但添加了一个@字符。仍然不喜欢抑制任何类型的错误或警告的想法。没有解决如果路径是字符串,如何访问的附加问题,但这不是主要问题。

<?php
$obj = new stdClass();
@$obj->foo[4]->bar[2]->fee->fi->fo->fum = 'hello';
echo($obj->foo[4]->bar[2]->fee->fi->fo->fum);