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

错误:

从空值创建默认对象

代码:

$res->success = false;

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


当前回答

试试这个:

ini_set('error_reporting', E_STRICT);

其他回答

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

$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.
}

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

首先你认为你应该创建对象 $res = new \stdClass(); 然后给object赋值为key和value $res->success = false;

您可能需要检查变量是否声明并具有正确的类型。

if (!isset($res) || !is_object($res)) {
    $res = new \stdClass();
    // With php7 you also can create an object in several ways.
    // Object that implements some interface.
    $res = new class implements MyInterface {};
    // Object that extends some object.
    $res = new class extends MyClass {};
} 

$res->success = true;

参见PHP匿名类。

试试这个:

ini_set('error_reporting', E_STRICT);

不,你不需要。当您将成功值添加到对象时,它将创建它。如果没有指定默认类,则继承默认类。