只有在将PHP环境升级到PHP 5.4或更高版本后,我才看到这个错误。错误指向这行代码:
错误:
从空值创建默认对象
代码:
$res->success = false;
我首先需要声明我的$res对象吗?
只有在将PHP环境升级到PHP 5.4或更高版本后,我才看到这个错误。错误指向这行代码:
错误:
从空值创建默认对象
代码:
$res->success = false;
我首先需要声明我的$res对象吗?
当前回答
您可能需要检查变量是否声明并具有正确的类型。
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 = (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不会对这行显示任何警告/通知。例如:
$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
我在开发时使用这个技巧。我不喜欢禁用所有警告消息,因为如果你不正确处理警告,那么他们将成为一个大错误在未来。
您可能需要检查变量是否声明并具有正确的类型。
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匿名类。