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

错误:

从空值创建默认对象

代码:

$res->success = false;

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


当前回答

试试这个:

ini_set('error_reporting', E_STRICT);

其他回答

这是我在PHP 7中遇到的一个警告,解决这个问题的简单方法是在使用变量之前初始化它

$myObj=new \stdClass();

一旦你初始化了它,你就可以将它用于对象

 $myObj->mesg ="Welcome back - ".$c_user;

简单地说,

    $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

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

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

从PHP 7开始,当变量为空时,可以使用空合并操作符来创建对象。

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

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

error_reporting(E_ERROR | E_PARSE);