Warning: Creating default object from empty value (typical solution not solving issue)

JMC picture JMC · Mar 15, 2017 · Viewed 7.4k times · Source

NOTE: I've read the other topics on stackoverflow about how to solve this issue: Creating default object from empty value in PHP?

For some reason I still get the Warning message: Creating default object from empty value

I've tried a few things to fix the warning:

$data = new stdClass();
$data->result->complex->first_key = $old_data->result->complex;

also tried:

$data->result->complex = new stdClass();
$data->result->complex->first_key = $old_data->result->complex;

Still get the warning: Creating default object from empty value on the line number of the new stdClass() initialization above.

Desired Outcome: How can I properly initialize the new empty object?

Answer

Sammitch picture Sammitch · Mar 15, 2017

If you want to avoid the warning you'll need to pre-create each level:

$data = new stdClass();
$data->result = new stdClass();
$data->result->complex = new stdClass();
$data->result->complex->first_key = $old_data->result->complex;