Sometimes it’s necessary to obtain the value of a protected or private property. Fortunately PHP 5.3 includes a new reflection method named setAccessible which allows us to do so.
The Method:
/**
* Get the value of a property using reflection.
*
* @param object|string $class
* The object or classname to reflect. An object must be provided
* if accessing a non-static property.
* @param string $propertyName The property to reflect.
* @return mixed The value of the reflected property.
*/
public static function getReflectedPropertyValue($class, $propertyName)
{
$reflectedClass = new ReflectionClass($class);
$property = $reflectedClass->getProperty($propertyName);
$property->setAccessible(true);
return $property->getValue($class);
}
Example Usages:
getReflectedPropertyValue($foo, 'myProtectedProperty');
getReflectedPropertyValue('Foo', 'myProtectedStaticProperty');
getReflectedPropertyValue('Foo\Bar', 'myProtectedStaticProperty');