Check out Scrivo

Do you want to try out Scrivo? Then here's a demo for you that does not just get your feet wet but lets you plunge right in.

Contact us

For more information, please contact us. We're happy to help you out!

Next Oct 3 Previous

OO and hipster beards

Those annoying front-end programmers with their hipster beards and designer shoes are currently porting the company's main application. The new version will be better, more intuitive, more responsive, clearer to the user, offer a better user experience, comply to web standards, use cutting edge technology, reduce server load, is indefinitely scalable, at least @ Web 3.0 if not Web π, have lots of social media integration, a mobile version and (drumrolls.....) a Twitter feed.

Luckily you can let them play in their sandbox with their jQuery shovels and HTML 5 buckets in the comforting knowledge that you can just dump your well thought out business objects into json_encode() to serve their XHR requests:

<?php

header("Content-type: application/json");

echo json_encode(new Account(intval($_GET["account_id"])));

?>

Or can't you?

p>A: Yes, that will keep'em busy for a while.
B: No, json_encode() will casts its argument to a string, so invoking the __toString() method of the Account class.
C: No, json_encode() will not find the private and protected properties of the class, and all my classes expose their members through accessor methods.
D: Nice try: there is no such media type.

What's your answer?

Answer

json_encode() will not automatically cast the given data to a string. If that is what you intent to do you'll have to do the cast yourself.

According to its RFC the correct media type is application/json.

json_encode() works well on scalar types and PHP arrays but when you use objects don't expect to get some var_dump() or serialze() type of output in JSON format. json_encode() will only find the public properties of an object which, if you adhere to the principles of object oriented design, should not be used.

And because we're in the business of real programming our objects will not reveal their properties through json_encode() and we can expect this program to output something like "{}". And that's not going to keep the beards away from your desk. Answer C is correct: you'll have to create some intermdieate array or object that contains the required data and use that one to create a JSON string.