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

错误:

从空值创建默认对象

代码:

$res->success = false;

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


当前回答

简单地说,

    $res = (object)array("success"=>false); // $res->success = bool(false);

或者你可以实例化类:

    $res = (object)array(); // object(stdClass) -> recommended

    $res = (object)[];      // object(stdClass) -> works too

    $res = new \stdClass(); // object(stdClass) -> old method

并使用以下语句填充值:

    $res->success = !!0;     // bool(false)

    $res->success = false;   // bool(false)

    $res->success = (bool)0; // bool(false)

更多信息: https://www.php.net/manual/en/language.types.object.php#language.types.object.casting

其他回答

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

error_reporting(E_ERROR | E_PARSE);

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

(一)$ this - > - >变量

(b) $ this - > my_variable

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

尝试使用:

$user = (object) null;

首先你认为你应该创建对象 $res = new \stdClass(); 然后给object赋值为key和value $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.
}

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