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

错误:

从空值创建默认对象

代码:

$res->success = false;

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


当前回答

此问题是由于您正在分配一个未初始化的对象实例而引起的。如:

你的情况:

$user->email = 'exy@gmail.com';

解决方案:

$user = new User;
$user->email = 'exy@gmail.com';

其他回答

如果你在行首放了“@”字符,那么PHP不会对这行显示任何警告/通知。例如:

$unknownVar[$someStringVariable]->totalcall = 10; // shows a warning message that contains: Creating default object from empty value

为了防止这一行的警告,你必须把“@”字符放在行开头,像这样:

@$unknownVar[$someStringVariable]->totalcall += 10; // no problem. created a stdClass object that name is $unknownVar[$someStringVariable] and created a properti that name is totalcall, and it's default value is 0.
$unknownVar[$someStringVariable]->totalcall += 10; // you don't need to @ character anymore.
echo $unknownVar[$someStringVariable]->totalcall; // 20

我在开发时使用这个技巧。我不喜欢禁用所有警告消息,因为如果你不正确处理警告,那么他们将成为一个大错误在未来。

此问题是由于您正在分配一个未初始化的对象实例而引起的。如:

你的情况:

$user->email = 'exy@gmail.com';

解决方案:

$user = new User;
$user->email = 'exy@gmail.com';

我把以下内容放在出错的PHP文件的顶部,错误不再显示:

error_reporting(E_ERROR | E_PARSE);

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

$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;