note 88790 deleted from function.json-encode by crell

From: Date: Thu, 30 Jun 2022 19:43:05 +0000
Subject: note 88790 deleted from function.json-encode by crell
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-218787@lists.php.net to get a copy of this message
Note Submitter: aangel at spam dot com ---- Here is a bit more on creating an iterator to get at those pesky private/protected variables: <?php class Kit implements IteratorAggregate { public function __construct($var) { if (is_object($var)) { // if passed an object, we are cloning $this->kitID = $var->kitID; $this->kitName = $var->kitName; foreach ($var->productArray as $key => $value) { $this->productArray[$key] = (array)$value; } } } ... // Create an iterator because private/protected vars can't // be seen by json_encode(). public function getIterator() { $iArray['kitID'] = $this->kitID; $iArray['kitName'] = $this->kitName; $iArray['productArray'] = (array)$this->productArray; return new ArrayIterator($iArray); } } ?> Calling something like $t = json_encode($this->getIterator()); will give you almost what you want: <?php {"kitID":"Kit_Essentials-Books.txt", "kitName":"Essential Books", "productArray":{"0470043601":{"Category":"Food","ASIN":"0470043601"} } } ?> Notice that the productArray is converted to an object ignoring the cast I put in front, which is not what I wanted. I haven't figured out how to make sure that encodes as an array. Regardless, bringing that JSON back into an object using json_decode() will give you just a std object, and the only way I've found to get it into the proper object type is to use a constructor that instantiates the object the way it's supposed to be (see __construct($var) above). Like this: <?php $newKit = new Kit(json_decode($t)); ?>

« previous php.notes (#218787) next »