如何修复 PHP Strict 错误“从空值创建默认对象”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1949966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:25:01  来源:igfitidea点击:

How do I fix the PHP Strict error "Creating default object from empty value"?

php

提问by Jake

I have the following PHP5 code:

我有以下 PHP5 代码:

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

Lines 2 and 3 are producing the following error:

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

PHP Strict standards: Creating default object from empty value

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

How can I fix this error?

我该如何解决这个错误?

回答by Yacoby

Null isn't an object, so you can't assign values to it. From what you are doing it looks like you need an associative array. If you are dead set on using objects, you could use the stdClass

Null 不是一个对象,所以你不能给它赋值。从你在做什么看起来你需要一个关联数组。如果您对使用对象死心塌地,则可以使用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";

I would recommend using arrays, as it is a neater syntax with (probably) the same underlying implementation.

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

回答by Brad

Get rid of $request = NULL and replace with:

去掉 $request = NULL 并替换为:

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

You are trying to write to NULL instead of an actual object.

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

回答by Richard Quinn

To suppress the error:

要抑制错误:

error_reporting(0);

To fix the error:

要修复错误:

$request = new stdClass();

hth

回答by Amber

Don't try to set attributes on a null value? Use an associative array instead.

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