Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
409 views
in Technique[技术] by (71.8m points)

Best way to create an empty object in JSON with PHP?

To create an empty JSON object I do usually use:

json_encode((object) null);

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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: Objects - Manual

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.


.. 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 ("{}"));

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 evaluate the following to true:

$a = <something>;

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

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...