【问题标题】:Warning: Creating default object from empty value (typical solution not solving issue)警告:从空值创建默认对象(典型解决方案未解决问题)
【发布时间】:2017-03-15 18:29:36
【问题描述】:

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

由于某种原因,我仍然收到警告消息:Creating default object from empty value

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

$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() 初始化的行号上。

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

【问题讨论】:

    标签: php object warnings php-5.4


    【解决方案1】:

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

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

    【讨论】:

    • 了解过程中发生了什么的最简单的答案。
    【解决方案2】:

    你仍然缺少“第一个”空对象

    $data->result = new stdClass();
    

    全部可以通过:

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

    或通过:

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

    【讨论】:

    • 感谢您提供替代语法选项。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多