PHP serializer in userland code
I did a bit of work on an alternative for serialize(), written in PHP.
I wanted to build this as a helper class for a draft-PHP-RPC server. The reason I needed a custom one was because I wanted to make sure I would be able to spit out PHP4-compatible serialized data, and in the future, when its ported to PHP6, also PHP5-compatible data.
Some of my findings:
- Its dead-slow, compared to the built-in version (as expected). What PHP's built in serializer could do in 0.00366 seconds, I needed 0.0948.
- So even though its CPU expensive, there is less memory needed for big structures, because it uses echo so it can stream it straight to the client if needed.
- When a property is private or protected, it really is. There's no way to grab the value. I was hoping Reflection would have allowed me to cheat.
- There's no proper way to find out if two variables reference the same data. The only way is to change one of them, and see if the second also changed.
- I was hoping SPLObjectStorage would be able to give me back an index the stored object. Instead I'm looping through all the objects I got and use === to see if they are the same.
I'm starting to wonder now if its a better idea to just use serialize() and make the needed fixes with regexes and stuff, but thats an experiment for an other night.
For the people who might find it useful, here's the download and source code..
List of differences with PHP's serialize:
- It only checks references for objects.
- It converts Serializable objects to strings when the target version is PHP4.
- It has a setting that allows you to automatically convert any object to an array or STDClass.
- It ignores all private and protected variables.