1

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?

2 Answers 2

7

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;
Sign up to request clarification or add additional context in comments.

1 Comment

Easiest answer to understand what's going on in the process.
1

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']]]));

1 Comment

Thanks for providing alternate syntax options.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.