从PHP中的空值创建默认对象? [英] Creating default object from empty value in PHP?
问题描述
仅在将我的PHP环境升级到PHP 5.4及更高版本后,我才看到此错误.错误指向以下代码行:
I see this error only after upgrading my PHP environment to PHP 5.4 and beyond. The error points to this line of code:
错误:
从空值创建默认对象
Creating default object from empty value
代码:
$res->success = false;
我首先需要声明我的$res
对象吗?
Do I first need to declare my $res
object?
推荐答案
Your new environment may have E_STRICT
warnings enabled in error_reporting
for PHP versions <= 5.3.x, or simply have error_reporting
set to at least E_WARNING
with PHP versions >= 5.4. That error is triggered when $res
is NULL
or not yet initialized:
$res = NULL;
$res->success = false; // Warning: Creating default object from empty value
如果$res
已经初始化为某个值但不是对象,则
PHP将报告不同的错误消息:
PHP will report a different error message if $res
is already initialized to some value but is not an object:
$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
的对象:
In order to comply with E_STRICT
standards prior to PHP 5.4, or the normal E_WARNING
error level in PHP >= 5.4, assuming you are trying to create a generic object and assign the property success
, you need to declare $res
as an object of stdClass
in the global namespace:
$res = new \stdClass();
$res->success = false;
这篇关于从PHP中的空值创建默认对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!