Using PHP Reflection to read a Protected Property

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);

    return $property->getValue($class);

Example Usages:

getReflectedPropertyValue($foo, 'myProtectedProperty');
getReflectedPropertyValue('Foo', 'myProtectedStaticProperty');
getReflectedPropertyValue('Foo\Bar', 'myProtectedStaticProperty');

Leave a Reply

Your email will not be published. Name and Email fields are required.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>