Consider the following code.
$car = (object)[
'general' => [
'interior' => [
'seats' => 'destroyed'
]
]
];
$exteriorProperties = [
'hood' => 'shiny',
'windows' => 'dirty'
];
foreach($exteriorProperties as $key => $prop){
$car->{'other'}->{'exterior'}->{$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 => $prop){
if(!isset($car->other))
$car->other = (object)[];
if(!isset($car->other->exterior))
$car->other->exterior = (object)[];
$car->other->exterior->{$key} = $prop;
}
This is not my ideal solution. I'm wondering if there's a more elegant solution. Currently, I'm using this:
@$car->{'other'}->{'exterior'}->{$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?