Accessing data in protected and private properties
Today I decided to look though a small trick by Derick Rethans on how to access private properties in PHP and I ended up making a function to collect Reflection-like information and wanted to share the source:
* Provides reflection-like information to expose an
* objects properties.
* Based on trick to access private properties by
* Derick Rethans.
* @param object The object to inspect
* @return array Returns an array on succes and false on error
To explain the trick in detail, the main trick is in this line:
$cast = (array) $object;
When casting an object to an array it will expose the values of its properties no matter of the visibility level. All private and protected properties's index will begin with a NUL character (\0). For protected properties the NUL character will be followed by a * character and another NUL character and then its property name. For private properties the first character is a NUL character and then the class name and another NUL character and then its property name. All other indexes are public (either using public or var keywords).
Its also however possible to change the values, BUT when you cast them back to an object the class will be changed to an instance of the 'stdClass' class and therefore it will loose all its methods and isn't useful any longer, so this trick is mainly for debugging proposes ;)
Hope this will help some!
The Following User Says Thank You to Kalle For This Useful Post:
On a side note. If you have wrote your program in such a way that you ever need to bring private class variables outside of the class, you need to rethink your design. Private variables are made for the specific purpose of not being seen by anything, so to need to see them is a sign of bad architecture.