在 PHP 中从空值创建默认对象? [英] Creating default object from empty value in PHP?

查看:27
本文介绍了在 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:

错误:

从空值创建默认对象

代码:

$res->success = false;

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

Do I first need to declare my $res object?

推荐答案

您的新环境可能有 E_STRICT 警告 error_reporting 中为 PHP 版本 <= 5.3.x 启用,或者只是有 error_reporting 至少设置为 E_WARNING,PHP 版本 >= 5.4.当 $resNULL 或尚未初始化时会触发该错误:

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,需要在全局命名空间中声明$resstdClass的对象:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆