note 98718 deleted from function.json-encode by crell

From: Date: Fri, 01 Jul 2022 19:20:37 +0000
Subject: note 98718 deleted from function.json-encode by crell
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-218829@lists.php.net to get a copy of this message
Note Submitter: mic dot sumner at gmail dot com ---- 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!

« previous php.notes (#218829) next »