Reflecting private properties - Blog - Open Source - schlitt.info

schlitt.info - php, photography and private stuff

Reflecting private properties

I recently stumbled over reflecting private properties in PHP again. As you might know, this was not possible until now and if you tried this:

<?php class Foo { private $bar = 23; } $obj = new Foo(); $refObj = new ReflectionObject( $obj ); $refProp = $refObj->getProperty( 'bar' ); echo $refProp->getValue( $obj ); ?>

PHP thanked it to you with this:

ReflectionException: Cannot access non-public member Foo::bar in /home/dotxp/dev/ez/ezcomponents/trunk/reflection.php on line 12

While it is absolutly correct that direct access to private properties is strictly forbidden, it is quite disturbing that even reflection cannot do it when you do metaprogramming where accessing private properties can be essential. Today things changed for PHP 5.3 and 6, after Derick and me managed to convince Marcus and Derick provided a patch. You still need to explicitly state that you want to access the value of a protected/private property through reflection by the new method setAccessible() (which is a good thing to avoid people doing stupid things accedentally), but you finally get the access to it:

<?php class Foo { private $bar; } $obj = new Foo(); $refObj = new ReflectionObject( $obj ); $refProp = $refObj->getProperty( 'bar' ); // Gather access to this properties value, although it is private $refProp->setAccessible( true ); echo $refProp->getValue( $obj ); ?>

This code should not throw an exception to you, but print the desired 23 value.

Thanks to Marcus and Derick for getting this finally done, so that we can soon forget about ugly hacks in the metaprogramming and testing area.

If you liked this blog post or learned something, please consider using flattr to contribute back: .

Trackbacks

Comments

Add new comment

Fields with bold names are mandatory.