Jump to content

arrayaccess + Iterator + json_encode = :wtf:


nicholasstephan

Recommended Posts

Ok - a bit of a boggle for the mind here: I'm implementing arrayaccess and Iterator to create a class that mimics array functionality, and works in loops (http://us.php.net/manual/en/class.arrayaccess.php and http://us.php.net/manual/en/class.iterator.php).

 

This works great most of the time, you can traverse the tree with []'s and plug it into a foreach loop and control the output with rewind(), valid(), current()... functions.

 

Where the thing is falling over is when I try to encode it as JSON. Does anybody know how json_encode() is gathering it's data. It's not looping through the content the same way foreach does. What it ends up doing is giving me a json string representing all the public internal variables in my class, rather than the data the class is supposed to hold.

 

WTF

 

 

Link to comment
https://forums.phpfreaks.com/topic/179656-arrayaccess-iterator-json_encode-wtf/
Share on other sites

That's the way json_encode works on objects. Implementing arrayaccess adds some functionality to your class, but it doesn't make it an array.

 

You could add toArray() method to your class, that will return contents of the container as an array.

You can also cast your object to (array) and then json_encode it's container.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.