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

错误:

从空值创建默认对象

代码:

$res->success = false;

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


当前回答

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

$res = $res ?? new \stdClass();
$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匿名类。

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

在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不会对这行显示任何警告/通知。例如:

$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

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

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