note 98718 added to function.json-encode

From: Date: Fri, 02 Jul 2010 13:39:38 +0000
Subject: note 98718 added to function.json-encode
Groups: php.notes 
Request: Send a blank email to php-notes+get-170653@lists.php.net to get a copy of this message
Hey everyone, In my application, I had objects that modeled database rows with a few one to many relationships, so one object may have an array of other objects. I wanted to make the object properties private and use getters and setters, but I needed them to be serializable to json without losing the private variables. (I wanted to promote good coding practices but I needed the properties on the client side.) Because of this, I needed to encode not only the normal private properties but also properties that were arrays of other model objects. I looked for awhile with no luck, so I coded my own: You can place these methods in each of your classes, or put them in a base class, as I've done. (But note that for this to work, the children classes must declare their properties as protected so the parent class has access) <?php abstract class Model { public function toArray() { return $this->processArray(get_object_vars($this)); } private function processArray($array) { foreach($array as $key => $value) { if (is_object($value)) { $array[$key] = $value->toArray(); } if (is_array($value)) { $array[$key] = $this->processArray($value); } } // If the property isn't an object or array, leave it untouched return $array; } public function __toString() { return json_encode($this->toArray()); } } ?> Externally, you can just call <?php echo $theObject; //or echo json_encode($theObject->toArray()); ?> And you'll get the json for that object. Hope this helps someone! ---- Server IP: 69.147.83.197 Probable Submitter: 152.23.62.112 ---- Manual Page -- http://www.php.net/manual/en/function.json-encode.php Edit -- https://master.php.net/note/edit/98718 Del: integrated -- https://master.php.net/note/delete/98718/integrated Del: useless -- https://master.php.net/note/delete/98718/useless Del: bad code -- https://master.php.net/note/delete/98718/bad+code Del: spam -- https://master.php.net/note/delete/98718/spam Del: non-english -- https://master.php.net/note/delete/98718/non-english Del: in docs -- https://master.php.net/note/delete/98718/in+docs Del: other reasons-- https://master.php.net/note/delete/98718 Reject -- https://master.php.net/note/reject/98718 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#170653) next »