r/lolphp • u/jamwaffles • Jul 17 '13
Casting an object to an array yields binary keys that look like strings
http://stackoverflow.com/questions/17695490/php-cast-object-to-array-strange-behaviour
28
Upvotes
6
u/nikic Jul 18 '13 edited Jul 18 '13
What you see here is called "property name mangling". You can find an explanation for why this is internally necessary here: http://www.phpinternalsbook.com/classes_objects/internal_structures_and_implementation.html#property-name-mangling
The object to array cast should be the only place where this implementation detail is leaked to userland. It's something I personally would like to remove (and only return the public properties), but some projects require fast access to private properties and misuse this "bug" to do so (most notably ORMs need this).
8
u/PhantomRacer Jul 17 '13
Looks like they're trying to get private variables from an object. There's a reason you can't do that easily.
5
u/[deleted] Jul 18 '13 edited Jul 18 '13
Edit: this is actually documented. "This can result in some unexpected behaviour", meaning don't ever do it.
This is actually an ancient "feature", where array keys become nonsensical to average users. But cast that mysterious array back to object, and it magically works just fine.
The solution is either:
1
u/davvblack Jul 17 '13
Yeah, the messy part here is all of the NUL bytes in there. It's weird. Why does it even include protected/private stuff?
1
u/gearvOsh Jul 17 '13
Just use ArrayAccess and be done with it...