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:
PHP Code:
<?php
/**
* Reflector
*
* 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
*/
function Reflector($object)
{
if(!is_object($object))
{
return(false);
}
$retval = Array(
'class' => get_class($object),
'public' => Array(),
'protected' => Array(),
'private' => Array()
);
$cast = (array) $object;
if(!sizeof($cast))
{
return($retval);
}
$class = get_class($object);
$class_len = strlen($class);
foreach($cast as $property => $value)
{
if($property{0} == "\0")
{
if($property{1} == '*')
{
$retval['protected'][substr($property, 3)] = $value;
}
elseif(substr($property, 1, $class_len) == $class)
{
$retval['private'][substr($property, $class_len + 2)] = $value;
}
}
else
{
$retval['public'][$property] = $value;
}
}
return($retval);
}
?>
To explain the trick in detail, the main trick is in this line:
PHP Code:
...
$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!