用PHP在JSON中创建空对象的最佳方法? [英] Best way to create an empty object in JSON with PHP?

查看:179
本文介绍了用PHP在JSON中创建空对象的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通常使用以下方法创建一个空的JSON对象:

To create an empty JSON object I do usually use:

json_encode((object) null);

向对象广播null可以,但是此解决方案是否还有其他更好的方法和/或任何问题?

casting null to an object works, but is there any other preferable way and/or any problem with this solution?

推荐答案

您的解决方案可以工作..

文档指定(object) null将导致一个空对象,因此有人可能会说您的代码有效,这是使用的方法.

Your solution could work..

The documentation specifies that (object) null will result in an empty object, some might therefor say that your code is valid and that it's the method to use.

PHP:对象-手册

如果将任何其他类型的值转换为对象,则会创建stdClass内置类的新实例.如果该值为NULL,则新实例将为空.

If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created. If the value was NULL, the new instance will be empty.


..但是,请确保安全!

尽管您永远不知道上述内容何时/是否会更改,所以如果您想100%地确定自己将始终在编码数据中以{}结尾,则可以使用以下方法:


.. but, try to keep it safe!

Though you never know when/if the above will change, so if you'd like to be 100% certain that you will always will end up with a {} in your encoded data you could use a hack such as:

json_encode (json_decode ("{}"));

即使这很繁琐又丑陋,我还是假设/希望json_encode/json_decode与彼此兼容,并且总是将以下内容评估为真:

Even though it's tedious and ugly I do assume/hope that json_encode/json_decode is compatible with one and other and always will evalute the following to true:

$a = <something>;

$a === json_decode (json_encode ($a)); 


推荐方法

json_decode ("{}")默认情况下将返回stdClass,因此应使用以下内容将其视为安全.但是,正如所提到的,它与(object) null差不多.


Recommended method

json_decode ("{}") will return a stdClass per default, using the below should therefor be considered safe. Though, as mentioned, it's pretty much the same thing as doing (object) null.

json_encode (new stdClass);

这篇关于用PHP在JSON中创建空对象的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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