警告:从空值创建默认对象(典型解决方案未解决问题)

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

注意: 我已经阅读了有关如何解决此问题的 Whosebug 上的其他主题: Creating default object from empty value in PHP?

出于某种原因,我仍然收到警告消息:正在从空值创建默认对象

我已经尝试了一些方法来修复警告:

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

也尝试过:

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

仍然收到警告:Creating default object from empty value 在上面新的 stdClass() 初始化的行号上。

期望的结果: 如何正确初始化新的空对象?

你还缺少"first"个空对象

$data->result = new stdClass();

全部可以通过以下方式完成:

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

或通过:

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

如果您想避免警告,您需要预先创建每个关卡:

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