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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Recommended method
json_decode ("{}")will return astdClassper default, using the below should therefor be considered safe/portable and correct.Your solution could work..
The documentation specifies that
(object) nullwill result in an empty object, some might therefor say that your code is valid and that it’s the method to use... 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:Even though it’s tedious and ugly I do assume/hope that json_encode/json_decode is compatible with one another and always will evaluate the following to true: