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

错误:

从空值创建默认对象

代码:

$res->success = false;

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


当前回答

尝试使用:

$user = (object) null;

其他回答

您的新环境可能在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;

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

error_reporting(E_ERROR | E_PARSE);

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

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

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

这是我在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