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

℡╲_俬逩灬. 提交于 2020-01-15 09:53:08

问题


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?


回答1:


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;



回答2:


You are still missing "first" empty object

$data->result = new stdClass();

Whole can be done by:

$data = (object)['result' => (object)['complex' => (object)['first_key' => 'value']]];

Or by:

$data = json_decode(json_encode(['result' => [complex' => ['first_key' => 'value']]]));


来源:https://stackoverflow.com/questions/42817923/warning-creating-default-object-from-empty-value-typical-solution-not-solving

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!