JQuery Venetian Blinds Transition Effect
Using PHP pspell Spell Check Functions with a Custom Dictionary
Using Multi-Byte Character Sets in PHP (Unicode, UTF-8, etc)
Installing Xdebug for use with Eclipse or Netbeans on Linux
Enforce Coding Standards with PHP_CodeSniffer and Eclipse IDE on Ubuntu Linux
Scrollable Tables with Floating Header using CSS

JSON Encode your Classes in PHP

Monday, 22 June 15, 1:38 pm
The built-in json_encode() function doesn't by default include any of your own classes' properties, and all you'll see is an empty pair of curly braces.

PHP 5.4 introduced the JsonSerializable interface to rectify this. It defines a single method called jsonSerialize() where you specify how your class should be converted to JSON.

Whatever this method returns is what will appear in the encoded output of json_encode(). You can return a number, a string, an array or an associative array. Only if you return an associative array will your class actually be encoded as a class in JSON notation.

Normally, you'll probably want your class to be encoded as a class with all its properties present, in which case you can use PHP's get_object_vars() like so:
class Customer implements JsonSerializable { private $id; private $accountRef;   public function setId($id) { $this->id = $id; }   public function setAccountRef($accountRef) { $this->accountRef = $accountRef; }   public function jsonSerialize() { return get_object_vars($this); }   }
 
Leave Comment

/xkcd/ Russell's Teapot

About This Page