【问题标题】:How do I fix the PHP Strict error "Creating default object from empty value"?如何修复 PHP Strict 错误“从空值创建默认对象”?
【发布时间】:2010-12-29 07:53:54
【问题描述】:

我有以下 PHP5 代码:

$request = NULL;
$request->{"header"}->{"sessionid"}        =  $_SESSION['testSession'];
$request->{"header"}->{"type"}             =  "request";

第 2 行和第 3 行产生以下错误:

PHP 严格标准:从空值创建默认对象

我该如何解决这个错误?

【问题讨论】:

  • 只是好奇,你以前在哪里看到过这种风格? $request->{"header"}->{"sessionid"}
  • 我在构建 JSON 请求时看到了它。

标签: php


【解决方案1】:

Null 不是一个对象,所以你不能给它赋值。从你所做的看起来你需要一个associative array。如果您不喜欢使用对象,可以使用stdClass

//using arrays
$request = array();
$request["header"]["sessionid"]        =  $_SESSION['testSession'];
$request["header"]["type"]             =  "request";

//using stdClass
$request = new stdClass();
$request->header = new stdClass();
$request->header->sessionid        =  $_SESSION['testSession'];
$request->header->type             =  "request";

我建议使用数组,因为它是一种更简洁的语法,具有(可能)相同的底层实现。

【讨论】:

  • 我无法让它与 stdClass() 一起使用。但是,array() 样式工作得很好……谢谢
【解决方案2】:

去掉 $request = NULL 并替换为:

$request = new stdClass;
$request->header = new stdClass;

您正在尝试写入 NULL 而不是实际对象。

【讨论】:

    【解决方案3】:

    抑制错误:

    error_reporting(0);
    

    修复错误:

    $request = new stdClass();
    

    【讨论】:

      【解决方案4】:

      不要尝试在空值上设置属性?请改用关联数组。

      【讨论】:

        猜你喜欢
        • 2013-09-29
        • 2019-03-26
        • 2018-12-22
        • 2019-01-15
        • 2016-10-11
        • 1970-01-01
        • 2013-01-26
        • 2017-09-30
        • 1970-01-01
        相关资源
        最近更新 更多