我仅在将我的 PHP 环境升级到 PHP 5.4 及更高版本后才看到此错误。错误指向这行代码:
错误:
Creating default object from empty value
代码:
$res->success = false;
我首先需要声明我的 $res
对象吗?
最佳答案
您的新环境可能有 E_STRICT
警告 enabled in error_reporting
对于 PHP 版本 <= 5.3.x,或者简单地将 error_reporting
设置为至少 E_WARNING
且 PHP 版本 >= 5.4。当 $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 - 从 PHP 中的空值创建默认对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8900701/