Private Properties Exposed

For our Components project we are ofcourse writing unit tests (with PHPUnit ). Sometimes you would want to test whether a private property contains the correct data, and of course with the normal visibility rules you can't access those from your unit test. There is an interesting trick for this, which I'll share here:

<?php
class foo {
    private $bar = 42;
}
$obj = new foo;
$propname="\0foo\0bar";
$a = (array) $obj;
echo $a[$propname];
?>


Comments

static function expose($obj, $prop)
{
$reflection = new ReflectionClass($obj);
$prop = $reflection->getProperty($prop);
return $prop->getValue($obj);

}

$f->{"0Foo0id"} (for private members) and $f->{"0*0name"} (for protected ones) used to work. Too bad someone added a "Cannot access property started with '0'" fatal error to the Zend Engine in the meantime, making necessary the array-cast hack presented here...

I'd rather have ReflectionProperty->setAccessible(TRUE) like (insert other programming language here):)

Add Comment

Name:
Email:

Will not be posted
Comment:

Please follow the reStructured Text format


All comments are moderated

Life Line