只有在将PHP环境升级到PHP 5.4或更高版本后,我才看到这个错误。错误指向这行代码:

错误:

从空值创建默认对象

代码:

$res->success = false;

我首先需要声明我的$res对象吗?


当前回答

我也有类似的问题,这似乎解决了问题。你只需要将$res对象初始化为一个类。假设这里的类名是test。

class test
{
   //You can keep the class empty or declare your success variable here
}
$res = new test();
$res->success = false;

其他回答

如果您有数组并向其添加对象,请尝试此方法。

$product_details = array();

foreach ($products_in_store as $key => $objects) {
  $product_details[$key] = new stdClass(); //the magic
  $product_details[$key]->product_id = $objects->id; 
   //see new object member created on the fly without warning.
}

这将发送数组对象供以后使用~!

尝试使用:

$user = (object) null;

在PHP 7中,匿名对象可以这样创建:

$res = new class {
    public $success = false;
};

https://www.php.net/manual/en/language.oop5.anonymous.php http://sandbox.onlinephpfunctions.com/code/ab774707a8219c0f35bdba49cc84228b580b52ee

得到这个错误的一个简单方法是输入下面的(A),意思是输入(b)

(一)$ this - > - >变量

(b) $ this - > my_variable

微不足道,但很容易被忽视,如果你不去寻找,就很难发现。

您的新环境可能在PHP版本<= 5.3的error_reporting中启用了E_STRICT警告。在PHP版本>= 5.4中,或者简单地将error_reporting设置为至少E_WARNING。当$res为NULL或尚未初始化时触发该错误:

$res = NULL;
$res->success = false; // Warning: Creating default object from empty value

如果$res已经初始化为某个值但不是一个对象,PHP将报告一个不同的错误消息:

$res = 33;
$res->success = false; // Warning: Attempt to assign property of non-object

为了符合PHP 5.4之前的E_STRICT标准,或者符合PHP >= 5.4中正常的E_WARNING错误级别,假设你试图创建一个泛型对象并分配属性success,你需要在全局命名空间中将$res声明为stdClass的对象:

$res = new \stdClass();
$res->success = false;