Creating default object from empty value in PHP? Consider the following code.

$car = (object)[
   'general' =&gt; [
        'interior' =&gt; [
            'seats' =&gt; 'destroyed'
        ]
    ]
];

$exteriorProperties = [
    'hood' =&gt; 'shiny',
    'windows' =&gt; 'dirty'
];

foreach($exteriorProperties as $key =&gt; $prop){
    $car-&gt;{'other'}-&gt;{'exterior'}-&gt;{$key} = $prop;
}


This is a scenario where I'd like to add properties to an object, a few layers deep at a time, while iterating through some other data. If it doesn't exist, it will just create it, if it does it will override. PERFECT!

Unfortunately, this will throw the warning:


  Creating default object from empty value


I could resolve the issue by checking first if the property exists like so:

foreach($exteriorProperties as $key =&gt; $prop){
    if(!isset($car-&gt;other))
        $car-&gt;other = (object)[];
    if(!isset($car-&gt;other-&gt;exterior))
        $car-&gt;other-&gt;exterior = (object)[];
    $car-&gt;other-&gt;exterior-&gt;{$key} = $prop;
}


This is not my ideal solution. I'm wondering if there's a more elegant solution. Currently, I'm using this:

@$car-&gt;{'other'}-&gt;{'exterior'}-&gt;{$key} = $prop;


to suppress the warnings but I'm worried about compatibility in the future.

Does anyone have a more elegant solution to this scenario?
Yes, use arrays.

$car = [
   'general' =&gt; [
        'interior' =&gt; [
            'seats' =&gt; 'destroyed'
        ]
    ]
];

$exteriorProperties = [
    'hood' =&gt; 'shiny',
    'windows' =&gt; 'dirty'
];

foreach($exteriorProperties as $key =&gt; $prop){
    $car['other']['exterior'][$key] = $prop;
}
$car = (object) $car;


Anyway, the object conversion will only convert the outermost array. The nested arrays are still arrays.

\is_array($car-&gt;general); // true


Why you need it to be shapeless objects anyway? Either define classes for those objects or treat them as arrays is the simple answer.

Btw $car-&gt;{'other'} is really weird way of writing $car-&gt;other...